【发布时间】:2015-10-19 17:41:42
【问题描述】:
我正在运行许多运行 Python 代码的 Google Compute Engine 实例,我想从实例中查找每个实例的名称或 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 命令行工具?
【问题讨论】:
标签: python google-compute-engine google-cloud-platform