GCP Python计算引擎列表VM

2024-06-06 11:45:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下Python3脚本:

import os, json
import googleapiclient.discovery
from google.oauth2 import service_account
from google.cloud import storage

storage_client = storage.Client.from_service_account_json('gcp-sa.json')
buckets = list(storage_client.list_buckets())
print(buckets)

compute = googleapiclient.discovery.build('compute', 'v1')

def list_instances(compute, project, zone):
    result = compute.instances().list(project=project, zone=zone).execute()
    return result['items'] if 'items' in result else None

list_instances(compute, "my-project", "my-zone")

只列出bucket而不列出其余的就可以了,这告诉我我的服务帐户(具有对整个项目的读取权限)应该可以工作。我现在如何列出虚拟机?使用上面的代码,我得到

raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started

这告诉我,我必须以某种方式传递服务帐户json。这怎么可能

谢谢


Tags: instancesfromimportprojectjsonzoneservicegoogle