我正在寻找所有活动资源(例如计算引擎,gke等)和相应区域。 我尝试使用以下python代码进行打印,但是只要有可用的计算引擎,它就会打印所有区域信息,请有人指导我可以使用哪些功能。
compute = googleapiclient.discovery.build('compute', 'v1')
request = compute.instances().aggregatedList(project=project)
while request is not None:
response = request.execute()
for name, instances_scoped_list in response['items'].items():
pprint((name, instances_scoped_list))
request = compute.instances().aggregatedList_next(previous_request=request, previous_response=response)
答案 0 :(得分:1)
您可以使用Cloud Console gcloud compute instances list
command或instances.list()
method列出项目中拥有的所有实例。
要以表格形式列出项目中的所有实例,请运行:
gcloud compute instances list
您会得到类似的东西:
NAME ZONE MACHINE_TYPE PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUS
instance-1 us-central1-a n1-standard-1 10.128.0.44 xx.xx.xxx.xx RUNNING
instance-2 us-central1-b n1-standard-1 10.128.0.49 xx.xx.xxx.xx RUNNING
正如您所提到的, aggregatedList()是正确的,要获得所需的信息,有必要遍历JSON响应正文。
如果您需要某些特定字段,可以检查Response body information。
此外,您可以将此代码用作指导,我将从实例中获取所有信息。
from pprint import pprint
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()
service = discovery.build('compute', 'v1', credentials=credentials)
# Project ID for this request.
project = "{Project-ID}" # TODO: Update placeholder value.
request = service.instances().aggregatedList(project=project)
while request is not None:
response = request.execute()
instance = response.get('items', {})
for instance in instance.values():
for a in instance.get('instances', []):
print(str(instance))
request = service.instances().aggregatedList_next(previous_request=request, previous_response=response)