Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 532
Sony Khan Avatar asked Aug 21 '19 10:08

Sony Khan


People also ask

What is Google API client library for Python?

The Google API Client Library for Python is designed for Python client-application developers. It offers simple, flexible access to many Google APIs.


1 Answers

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)
like image 143
John Hanley Avatar answered Sep 19 '22 18:09

John Hanley