【发布时间】:2019-05-02 21:29:24
【问题描述】:
我想使用 Python 获取我在 Google Cloud 上的所有 Dataproc 集群的列表。
我的服务帐户凭据存储在 JSON 密钥文件中,其位置由 env var GOOGLE_APPLICATION_CREDENTIALS 引用。这是我到目前为止的代码:
import os
import googleapiclient.discovery
from oauth2client.client import GoogleCredentials
def build_dataproc_service(credentials):
return googleapiclient.discovery.build("dataproc", "v1", credentials=credentials)
def list_clusters():
credentials = GoogleCredentials.get_application_default()
dataproc = build_dataproc_service(credentials)
clusters = dataproc.projects().regions().clusters().list(projectId="my-project", region="REGION").execute()
return clusters
if __name__ == "__main__":
list_clusters()
如您所见,我已经硬编码了 projectId ("my-project")。鉴于 projectId 存在于 JSON 密钥文件中,我希望我可以通过询问 credentials 对象的属性来获得它,但不存在这样的属性。 projectId 确实 存在嵌入在 credentials._service_account_email 字符串属性中,但从那里提取它很笨重并且感觉不对。
我认为一定有更好的方法。如何获取服务帐号所在项目的projectId?
请注意,最初我打算将此代码在 Google Compute Engine 实例上的 docker 容器中运行,但是将来有一天我可能希望在 GKE 上运行。不确定这是否会影响答案。
【问题讨论】:
标签: python google-compute-engine google-cloud-dataproc