简体   繁体   English

如何获取 GCP 中所有项目的所有 VM 信息

[英]How to get all the VM's information for all Projects in GCP

How to get all the VM's information for all Projects in GCP.如何获取 GCP 中所有项目的所有 VM 信息。

I have multiple Projects in My GCP account and I need the Operating System, Version of Operating of System and Build Version of the Operating System for All the VM's for all Project in GCP.我的 GCP 帐户中有多个项目,我需要 GCP 中所有项目的操作系统、系统操作系统版本和操作系统构建版本。

I didn't find a tool to that, so I code something that you can use.我没有找到一个工具,所以我编写了一些你可以使用的东西。 This code must be improved, but here you can find a way to scan all project and get information about the OS.此代码必须改进,但在这里您可以找到一种方法来扫描所有项目并获取有关操作系统的信息。

Let me know if it helps you.让我知道它是否对你有帮助。

Pip install:点安装:

!pip install google-cloud
!pip install google-api-python-client
!pip install oauth2client

Code:代码:

import subprocess
import sys
import logging
import threading
import pprint

logger = logging.Logger('catch_all')

def execute_bash(parameters):
    try:
        return subprocess.check_output(parameters)
    except Exception as e: 
       logger.error(e) 
       logger.error('ERROR: Looking in jupyter console for more information')

def scan_gce(project, results_scan):
    print('Scanning project: "{}"'.format(project))
    ex = execute_bash(['gcloud','compute', 'instances', 'list', '--project', project, '--format=value(name,zone, status)'])
    list_result_vms = []
    if ex:
        list_vms = ex.decode("utf-8").split('\n')
        for vm in list_vms:
            if vm:
                vm_info = vm.split('\t')
                print('Scanning Instance: "{}" in project "{}"'.format(vm_info[0], project))
                results_bytes = execute_bash(['gcloud', 'compute', '--project',project, 
                                        'ssh', '--zone', vm_info[1],  vm_info[0], 
                                        '--command', 'cat /etc/*-release'  ])
                if results_bytes:
                    results = results_bytes.decode("utf-8").split('\n')
                    list_result_vms.append({'instance_name': vm_info[0],'result':results})


    results_scan.append({'project':project, 'vms':list_result_vms})


list_projects = execute_bash(['gcloud','projects', 'list', '--format=value(projectId)']).decode("utf-8").split('\n')
threads_project = []
results_scan = []
for project in list_projects :
    t = threading.Thread(target=scan_gce, args=(project, results_scan))
    threads_project.append(t)
    t.start()

for t in threads_project:
    t.join()

for result in results_scan:
    pprint.pprint(result)

You can find the full code here :你可以在这里找到完整的代码:

Wuick and dirty:又脏又臭:

gcloud projects list --format 'value(PROJECT_ID)' >> proj_list

cat proj_list | while read pj; do gcloud compute instances list --project $pj; done

You can use the following command in the Cloud Shell to fetch all projects and then show the instances for each of them:您可以在 Cloud Shell 中使用以下命令来获取所有项目,然后显示每个项目的实例:

for i in $(gcloud projects list |  sed 1d | cut -f1 -d$' '); do 
gcloud compute instances list --project $i;done;

note: make sure you have compute.instances.list permission to all of the projects注意:确保您对所有项目都拥有 compute.instances.list 权限

Here is how you do it using the pip3 install -U google-api-python-client without using bash. Note, this is to be ran with keyless auth.这是使用pip3 install -U google-api-python-client而不使用 bash 的方法。请注意,这是使用无密钥身份验证运行的。 Using service account keys is bad practice.使用服务帐户密钥是不好的做法。

https://github.com/googleapis/google-api-python-client/blob/main/docs/start.md https://github.com/googleapis/google-api-python-client/blob/main/docs/dyn/index.md https://googleapis.github.io/google-api-python-client/docs/dyn/compute_v1.html https://github.com/googleapis/google-api-python-client/blob/main/docs/start.md https://github.com/googleapis/google-api-python-client/blob/main/docs /dyn/index.md https://googleapis.github.io/google-api-python-client/docs/dyn/compute_v1.html

from googleapiclient import discovery
from googleapiclient.errors import HttpError
import yaml
import structlog

logger = structlog.stdlib.get_logger()

def get_projects() -> list:
    projects: list = []
    service = discovery.build('cloudresourcemanager','v1', cache_discovery=False)

    request = service.projects().list()
    response = request.execute()

    for project in response.get('projects'):
            projects.append(project.get("projectId"))

    logger.debug('got projects', projects=projects)
    return projects

def get_zones(project: str) -> list:
    zones: list = []
    service = discovery.build('compute','v1', cache_discovery=False)

    request = service.zones().list(project=project)

    while request is not None:
        response = request.execute()
        if not 'items' in response:
            logger.warn('no zones found')
            return {}

        for zone in response.get('items'):
            zones.append(zone.get('name'))

        request = service.zones().list_next(previous_request=request,previous_response=response)

    logger.debug('got zones', zones=zones)
    return zones

def get_vms() -> list:
    vms: list = []
    projects: list = get_projects()
    service = discovery.build('compute', 'v1', cache_discovery=False)

    for project in projects:
        try:
            zones: list = get_zones(project)

            for zone in zones:
                request = service.instances().list(project=project, zone=zone)
                response = request.execute()

                if 'items' in response:
                    for vm in response.get('items'):
                        ips: list = []

                        for interface in vm.get('networkInterfaces'):
                            ips.append(interface.get('networkIP'))

                        vms.append({vm.get('name'): {'self_link': vm.get('selfLink'), 'ips': ips}})

        except HttpError:
            pass

    logger.debug('got vms', vms=vms)
    return vms

if __name__ == '__main__':
    data = get_vms()

    with open('output.yaml', 'w') as fh:
        yaml.dump(data, fh)

暂无
暂无

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

相关问题 如何列出 GCP 中属于特定组织的所有项目 - How to list all projects in GCP that belongs to a specific organization GCP - 如何在 GCP 中查看一个 VM 成本? 在计费帐户中,我看到所有计算引擎的成本 - GCP - How to see one VM costs in GCP? In billing account I see costs of all compute engine 如何列出我所有项目中的所有 VM 实例,并同时列出它们分配的 vCPU 和 memory? - How to list all VM instances in all my projects and also list their assigned vCPU and memory as well? 从 GCP 中的所有项目获取所有虚拟机的列表 - Getting a list of all VMs from all Projects in GCP 如何列出 GCP 中具有默认防火墙规则的所有 VPC? - How to list all VPC's in GCP that has default firewall rules? 如何列出/获取项目中所有 GCP 资源的“创建者”? - How to list/get the 'creator' of all GCP resource in a project? GCP - 使用 CLI 列出所有项目中所有计算引擎上的 package(Ops Agent)版本 - GCP - Use CLI to list version of package (Ops Agent) on all Compute Engines in all Projects GCP vm 实例元数据的规则是什么 - What are the rules for GCP vm instance's metadata 限制所有用户在 GCP/AWS/Azure 中将公共 IP 附加到 EC2/VM 的权限 - Restricting the permissions for all users of attaching a public IP to EC2/VM in GCP/AWS/Azure 如何在我的 GCP 组织中获取所有外部 IP 地址? - How can I get all External IP Addresses in my GCP organization?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM