我想使用python google client api google-api-python-client==1.7.11
获取项目中所有实例的列表
我正在尝试使用方法googleapiclient.discovery.build
进行连接,此方法需要凭据作为参数
我阅读了文档,但未获得凭证格式以及所需的凭证
任何人都可以解释什么凭证以及如何通过以建立gcp连接
最佳答案
您所需的凭据称为“服务帐户JSON key 文件”。这些是在Google Cloud Console中的IAM和管理/服务帐户下创建的。创建一个服务帐户并下载 key 文件。在下面的示例中,这是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)
关于python-3.x - 使用Python客户端库进行gcp计算API使用什么以及如何传递凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57589526/