列出 google 个云计算引擎活动实例

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 command or the instances.list() method

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

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 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)