Search code examples
python-3.xgoogle-cloud-platformgoogle-api-client

What and how to pass credential using using Python Client Library for gcp compute API


I want to get list of all instances in a project using python google client api google-api-python-client==1.7.11 Am trying to connect using method googleapiclient.discovery.build this method required credentials as argument

I read documentation but did not get crdential format and which credential it requires

Can anyone explain what credentials and how to pass to make gcp connection


Solution

  • The credentials that you need are called "Service Account JSON Key File". These are created in the Google Cloud Console under IAM & Admin / Service Accounts. Create a service account and download the key file. In the example below this is service-account.json.

    Example code that uses a service account:

    from googleapiclient import discovery
    from google.oauth2 import service_account
    
    scopes = ['https://www.googleapis.com/auth/cloud-platform']
    sa_file = 'service-account.json'
    zone = 'us-central1-a'
    project_id = 'my_project_id' # Project ID, not Project Name
    
    credentials = service_account.Credentials.from_service_account_file(sa_file, scopes=scopes)
    
    # Create the Cloud Compute Engine service object
    service = discovery.build('compute', 'v1', credentials=credentials)
    
    request = service.instances().list(project=project_id, zone=zone)
    while request is not None:
        response = request.execute()
    
        for instance in response['items']:
            # TODO: Change code below to process each `instance` resource:
            print(instance)
    
        request = service.instances().list_next(previous_request=request, previous_response=response)