How to initialize GoogleCredentials object without using credentials files created by gcloud auth login
Question: To connect to GCE i can use the credentials files created by _gcloud auth
login_. Like this:

    
    
    from oauth2client.client import GoogleCredentials
    from googleapiclient.discovery import build
    
    credentials = GoogleCredentials.get_application_default()
    compute = build('compute', 'v1', credentials=credentials)
    
    def list_instances(compute, project, zone):
        result = compute.instances().list(project=project, zone=zone).execute()
        return result['items']
    
    instances = list_instances(compute, 'project', 'zone')
    

Above code uses the credentials stored at ~/.config/gcloud

I would like to initialize GoogleCredentials object by directly setting values
inside the code. Like client_id, client_secret..

PS: Above code is from this link :
<https://cloud.google.com/compute/docs/tutorials/python-guide#gettingstarted>


Answer: There is another way to initialize GoogleCredentials object:

    
    
    from oauth2client.client import GoogleCredentials
    from googleapiclient.discovery import build
    from oauth2client.client import AccessTokenCredentials
    from urllib import urlencode
    from urllib2 import Request , urlopen, HTTPError
    import json
    
    def access_token_from_refresh_token(client_id, client_secret, refresh_token):
        request = Request('https://accounts.google.com/o/oauth2/token',
            data=urlencode({
                'grant_type': 'refresh_token',
                'client_id': client_id,
                'client_secret': client_secret,
                'refresh_token': refresh_token
            }),
            headers={
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': 'application/json'
            }
        )
        response = json.load(urlopen(request))
        return response['access_token']
    
    access_token = access_token_from_refresh_token('client_id', 'client_secret', 'refresh_token')
    
    credentials = AccessTokenCredentials(access_token, "MyAgent/1.0", None)
    
    compute = build('compute', 'v1', credentials=credentials)
    
    def list_instances(compute, project, zone):
        result = compute.instances().list(project=project, zone=zone).execute()
        return result['items']
    
    instances = list_instances(compute, 'project', 'zone')
    

\-- values for client_id, secret, refresh_token taken from
~/.config/gcloud/credentials

