获取当前 Google 计算实例的名称或 ID

Get the name or ID of the current Google Compute Instance

我正在 运行使用 Google 计算引擎实例 运行 Python 代码,我想找到每个实例的名称或 ID来自实例内部的实例。

我找到的一个解决方案是使用以下方法获取实例的内部 IP:

import socket
internal_ip = socket.gethostbyname(socket.gethostname())

然后我列出所有实例:

from oauth2client.client import GoogleCredentials
from googleapiclient.discovery import build

credentials = GoogleCredentials.get_application_default()
self.compute = build('compute', 'v1', credentials=credentials)
result = self.compute.instances().list(project=project, zone=zone).execute()

然后我遍历所有实例以检查内部 IP 是否与实例的 IP 匹配:

for instance in result["items"]:
    if instance["networkInterfaces"][0]["networkIP"] == internal_ip:
        internal_id = instance["id"]

这个可行,但有点复杂,有没有更直接的方法来实现同样的事情,例如使用 Google 的 Python 客户端库或 gcloud 命令行工具?

实例名称:

socket.gethostname()platform.node() 应 return 实例名称。您可能需要根据 OS.

进行一些解析

这对我在 Debian 和 Ubuntu 系统上有效:

import socket
gce_name = socket.gethostname()

但是,在 CoreOS 实例上,hostname 命令给出了实例名称和区域信息,因此您必须进行一些解析。

实例ID/名称/更多(推荐):

更好的方法是使用 Metadata server. This is the easiest way to get instance information, and works with basically any programming language or straight CURL. Here is a Python example using Requests.

import requests
metadata_server = "http://metadata/computeMetadata/v1/instance/"
metadata_flavor = {'Metadata-Flavor' : 'Google'}
gce_id = requests.get(metadata_server + 'id', headers = metadata_flavor).text
gce_name = requests.get(metadata_server + 'hostname', headers = metadata_flavor).text
gce_machine_type = requests.get(metadata_server + 'machine-type', headers = metadata_flavor).text

同样,您可能需要在这里做一些解析,但这真的很简单!

参考资料: How can I use Python to get the system hostname?

要获取您的实例名称,请从您的 VM 执行以下命令:

curl http://metadata.google.internal/computeMetadata/v1/instance/hostname -H Metadata-Flavor:Google

并获取您的实例 ID:

curl http://metadata.google.internal/computeMetadata/v1/instance/id -H Metadata-Flavor:Google

查看其他可用参数的文档:https://cloud.google.com/compute/docs/storing-retrieving-metadata#project_and_instance_metadata