google-cloud 使用 python api 获取实例 ID 和区域

google-cloud get instance id and zone with python api

如何获取当前 运行 instanceId,它是 运行 Python 应用程序中的区域。

Go 和 Java 是通过以下方式完成的,Python 中的等价物是什么?

去,

import metadata "cloud.google.com/go/compute/metadata"

func main(){
    println(metadata.InstanceID))
}

Java

String instanceId = com.google.cloud.MetadataConfig.getInstanceId()

在 Python 中需要更多编码。这是您需要做的,列出 Google Compute Engine 中的所有实例。实例的 ID 和区域。

  1. Using the Python Client Library 文档中,您可以看到 CreateListDelete 实例的示例代码。对于整个源代码,还有一个 link 到 GitHub。
  2. 要列出实例,您需要 PROJECT_IDZONE。这意味着您必须首先列出所有可用的 ZONES,然后列出每个 ZONE 中的所有实例(如果可用)。参考 Regions and Zones documentation for all the available zones and to Method: zones.list 的 Python 代码来列出它们。

我自己编写了一些代码,我有一个适合我的代码。你可以找到我的 code example here.

注意:代码将需要一些时间来执行,因为它正在每个可用实例中寻找所有可能的可用实例 ZONE

我找到了一个简单的解决方案:

 requests.get("http://metadata/computeMetadata/v1/instance/id",
         headers={'Metadata-Flavor': 'Google'}).text