I'm running a number of Google Compute Engine instances that run Python code, and I want to find the name or the ID of each instance from inside the instances.
One solution I've found is to get the internal IP of the instance using:
import socket
internal_ip = socket.gethostbyname(socket.gethostname())
Then I list all the instances:
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()
Then I iterate over all the instances to check if the internal IP matches the IP of an instance:
for instance in result["items"]:
if instance["networkInterfaces"][0]["networkIP"] == internal_ip:
internal_id = instance["id"]
This works but it's a bit complicated, is there a more direct way to achieve the same thing, e.g. using Google's Python Client Library or the gcloud command line tool?
答案 0 :(得分:18)
实例名称:
socket.gethostname()
或platform.node()
应返回实例的名称。您可能需要根据您的操作系统进行一些解析。
这对我在Debian和Ubuntu系统上有用:
import socket
gce_name = socket.gethostname()
但是,在CoreOS实例上,hostname
命令给出了实例的名称和区域信息,因此您必须进行一些解析。
实例ID /名称/更多(推荐):
更好的方法是使用Metadata server。这是获取实例信息的最简单方法,基本上适用于任何编程语言或直接CURL。这是一个使用Requests的Python示例。
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
同样,您可能需要在此处进行一些解析,但这非常简单!
答案 1 :(得分:0)
要获取实例名称,请从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