我想使用Python获取Google Cloud上所有Dataproc集群的列表。
我有存储在JSON密钥文件中的服务帐户凭据,其位置由环境变量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上运行。不确定这是否会影响答案。