Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 644
Vinay Avatar asked Jan 28 '26 10:01

Vinay


1 Answers

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:

like image 59
hkanjih Avatar answered Jan 31 '26 08:01

hkanjih



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!