如果您想获得在 GCP 中创建 VM 时配置的 RAM,我认为使用 Compute Engine Libs 会很有用。
首先安装所需的库:
pip install google-api-python-client
如果您只需要一个实例,这可能会有所帮助:
import googleapiclient.discovery
PROJECT_ID="project_id"
ZONE="zone_where_the_instance_is"
compute = googleapiclient.discovery.build('compute', 'v1')
instances = compute.instances().list(project=PROJECT_ID, zone=ZONE).execute()
for instance in instances['items']:
ram = compute.machineTypes().get(project=PROJECT_ID, zone=ZONE, machineType=instance['machineType'].rsplit('/', 1)[-1]).execute()['memoryMb']
print ("RAM -> {:.1f} GB".format(round(ram/1024,1)))
你会得到:
RAM -> 1.8 GB
从项目中的所有实例获取此信息的更通用方法如下:
首先添加这个额外的库:
pip install tabulate
然后:
import googleapiclient.discovery
from tabulate import tabulate
PROJECT_ID="project_id"
compute = googleapiclient.discovery.build('compute', 'v1')
zones = compute.zones().list(project=PROJECT_ID).execute()
configs=[]
for zone in zones['items']:
instances = compute.instances().list(project=PROJECT_ID, zone=zone['name']).execute()
if 'items' in instances:
for instance in instances['items']:
ram = compute.machineTypes().get(project=PROJECT_ID, zone=zone['name'], machineType=instance['machineType'].rsplit('/', 1)[-1]).execute()['memoryMb']
configs.append([instance['name'],str(round(ram/1024,1))+" GB"])
print(tabulate(configs, headers=["Instance name", "RAM"]))
这会打印出这样的东西:
Instance name RAM
--------------- ------
satellite 1.8 GB
这些脚本假定您之前已配置 Cloud SDK 的凭据。