繁体   English   中英

列出谷歌云计算引擎活动实例

[英]List google cloud compute engine active instance

我正在寻找所有活动资源(如计算引擎、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)

您可以使用 Cloud Console gcloud compute instances list 命令instances.list() 方法gcloud compute instances list项目中的所有实例。

要以表格形式列出项目中的所有实例,请运行:

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

编辑1

正如您所提到的, aggregatedList()是正确的,要获取所需的信息,必须遍历 JSON 响应正文。

如果您需要一些特定的字段,您可以查看Response body 信息

此外,您可以使用此代码作为指导,我从实例中获取所有信息。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM