使用 Python Client Library for gcp compute API 传递凭证的内容和方式

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

我想使用 python google 客户端 api google-api-python-client==1.7.11 获取项目中所有实例的列表 我正在尝试使用方法 googleapiclient.discovery.build 进行连接,此方法需要凭据作为参数

我阅读了文档,但没有获得证书格式以及它需要的证书

任何人都可以解释什么凭据以及如何传递以建立 gcp 连接

应用程序默认凭据在 Google API 客户端库中自动提供。 There you can find example using python, also check this documentation Setting Up Authentication for Server to Server Production Applications

您需要的凭据称为 "Service Account JSON Key File"。这些是在 IAM 和管理员/服务帐户下的 Google Cloud Console 中创建的。创建服务帐户并下载密钥文件。在下面的示例中,这是 service-account.json.

使用服务帐户的示例代码:

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)

根据最近的 GCP documentation

we recommend you use Google Cloud Client Libraries for your application. Google Cloud Client Libraries use a library called Application Default Credentials (ADC) to automatically find your service account credentials

如果您仍想手动设置它,您可以先创建一个服务帐户并授予所有必要的权限:

# A name for the service account you are about to create:
export SERVICE_ACCOUNT_NAME=your-service-account-name

# Create service account:
gcloud iam service-accounts create ${SERVICE_ACCOUNT_NAME} --display-name="Service Account for ai-platform-samples repo"

# Grant the required roles:
gcloud projects add-iam-policy-binding ${PROJECT_ID} --member serviceAccount:${SERVICE_ACCOUNT_NAME}@${PROJECT_ID}.iam.gserviceaccount.com --role roles/ml.developer
gcloud projects add-iam-policy-binding ${PROJECT_ID} --member serviceAccount:${SERVICE_ACCOUNT_NAME}@${PROJECT_ID}.iam.gserviceaccount.com --role roles/storage.objectAdmin

# Download the service account key and store it in a file specified by GOOGLE_APPLICATION_CREDENTIALS:
gcloud iam service-accounts keys create ${GOOGLE_APPLICATION_CREDENTIALS} --iam-account ${SERVICE_ACCOUNT_NAME}@${PROJECT_ID}.iam.gserviceaccount.com

完成后检查 ADC 路径是否设置正确:

echo $GOOGLE_APPLICATION_CREDENTIALS

设置了 ADC 路径后,您不需要从代码中导入服务访问密钥,这是不可取的,因此代码如下所示:

service = googleapiclient.discovery.build(<API>, <version>,cache_discovery=False)