我想使用python Google客户端api google-api-python-client==1.7.11
获取项目中所有实例的列表
我正在尝试使用方法googleapiclient.discovery.build
进行连接,该方法需要凭据作为参数
我阅读了文档,但没有获得凭证格式以及所需的凭证
谁能解释什么凭证以及如何建立gcp连接
答案 0 :(得分:4)
您所需的凭据称为“服务帐户JSON密钥文件”。这些是在Google Cloud Console中的IAM和管理/服务帐户下创建的。创建一个服务帐户并下载密钥文件。在下面的示例中,这是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)
答案 1 :(得分:0)
应用程序默认凭据会自动在Google API客户端库中提供。 There您可以找到使用python的示例,还请查看此文档Setting Up Authentication for Server to Server Production Applications。
答案 2 :(得分:0)
根据 GCP 最新documentation:
<块引用>我们建议您使用 Google Cloud 客户端库 应用。 Google Cloud 客户端库使用名为 应用程序默认凭据 (ADC) 可自动查找您的 服务帐号凭据
如果您仍想手动设置它,您可以先创建一个服务帐户并授予所有必要的权限:
# 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)