【问题标题】:How to get GCP vm instance total memory size using python? [closed]如何使用 python 获取 GCP vm 实例总内存大小? [关闭]
【发布时间】:2020-10-22 17:53:27
【问题描述】:

我想在 gcp 实例中运行 python 启动脚本,我想在其中获取 gcp 实例的总内存大小。

我已经尝试过 free -hgrep MemTotal /proc/meminfo 命令。但是,这个命令的问题是,我得到的 RAM 比我在创建实例时选择的实际内存大小要少一些(由于系统使用可能)。我想获得我在创建实例时选择的确切内存大小。 例如,“e2-standard-8”为“32 GB”,“n2-standard-4”为“16 GB”

也没有可用于获取 gcp 实例内存大小的元数据 url。

有什么办法吗?

【问题讨论】:

  • 请分享您的 python 脚本,以便我们查看您尝试过的内容。另外,你在哪里执行脚本,在 VM 中还是在 GCP 之外?
  • 我在 vm 中执行脚本。我在 python 中使用以下函数来获取内存大小: import psutil psutil.virtual_memory().total 我也尝试过 free -h 命令。
  • 我发现这个stack post 是关于在 Python 中获取当前 CPU 和 RAM 使用情况。这可能会有所帮助

标签: google-cloud-platform google-compute-engine google-api-python-client


【解决方案1】:

如果您想获得在 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 的凭据。

【讨论】:

  • 它解决了我的问题,谢谢:)
  • 有没有办法在 aws 中实现同样的目标?
  • 我建议为此创建一个新问题。
  • 当然@YeriPelona
猜你喜欢
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 2020-04-02
  • 1970-01-01
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 2021-12-12
相关资源
最近更新 更多