如何使用gcloud多个服务帐户?

fre*_*rik 25 google-compute-engine gcloud

我有两个Google Cloud服务帐户; 我的两个项目各一个.

# ACCOUNTS
editor@someproj-1.iam.gserviceaccount.com
editor@someproj-2.iam.gserviceaccount.com
Run Code Online (Sandbox Code Playgroud)

gcloud在执行命令之前,我可以告诉我需要使用哪个帐户:

gcloud set account [ACCOUNT]
Run Code Online (Sandbox Code Playgroud)

问题:我有什么方法可以配置gcloud,gsutil以便它们可以用于在各自项目中执行的操作,而不必一直手动在这些帐户之间切换?


我在一个项目中管理实例,我从另一个项目中的桶上传/下载文件.必须一直执行gcloud set_account [ACCOUNT]中间命令变得非常繁琐.

我需要在两个项目中同时运行长时间运行的命令,这使我认为如果激活/取消激活用于这些命令的帐户,我将陷入陷阱.

也许我唯一的选择是从两个不同的Docker容器运行google-cloud-sdk?

Zac*_*man 37

你有几个选择:

  • Cloud SDK遵循指定属性的环境变量.gcloud config set account是简写gcloud config set core/account,所以相应的属性是CLOUDSDK_CORE_ACCOUNT.

    你可以这样做:

    $ CLOUDSDK_CORE_ACCOUNT=email1@domain1.com gcloud ...
    $ CLOUDSDK_CORE_ACCOUNT=email2@domain2.com gcloud ...
    
    Run Code Online (Sandbox Code Playgroud)

    哪个可以让你得到你感兴趣的结果.

  • 如果您需要更改多个属性,则Cloud SDK会提供命名配置抽象.有关完整详细信息,请参阅文档,但您可以运行:

    $ gcloud config configurations create my-project1-config
    $ gcloud config configurations activate my-project1-config
    $ gcloud auth login  # or activate-service-account
    $ gcloud config set project project1  # and any other configuration you need to do
    $ 
    $ gcloud config configurations create my-project2-config
    $ gcloud config configurations activate my-project2-config
    $ gcloud auth login  # or activate-service-account
    $ gcloud config set project project2  # and any other configuration you need to do
    $
    $ CLOUDSDK_ACTIVE_CONFIG_NAME=my-project1-config gcloud ...
    $ CLOUDSDK_ACTIVE_CONFIG_NAME=my-project2-config gcloud ...
    
    Run Code Online (Sandbox Code Playgroud)
  • 在最极端的情况下,您可以维护单独的Cloud SDK配置目录.默认(在*nix上)是~/.config/gcloud:

    $ CLOUDSDK_CONFIG=/tmp/tmpconfig1 gcloud auth login
    $ CLOUDSDK_CONFIG=/tmp/tmpconfig2 gcloud auth login
    
    Run Code Online (Sandbox Code Playgroud)

  • 要添加到这个答案,gcloud支持--account和--configuration标志.可以通过`gcloud auth list`列出--account的可能值,并且可以通过`gcloud config configurations list`列出配置的可能值.但这两个标志不能与gsutil或bq一起使用. (3认同)

mbu*_*c91 18

Zachary的答案非常有用,但是有一种使用gcloud配置的简便方法。

运行gcloud config configurations list以显示您的配置列表。如果您还没有做任何事情,它只会列出default您当前的任何活动帐户,项目等。

使用以下命令创建新配置gcloud config configurations create [config name]

> gcloud config configurations create testconfig
Created [testconfig].
Activated [testconfig].
Run Code Online (Sandbox Code Playgroud)

现在,新配置将处于活动状态,因此请继续进行设置gcloud init

> gcloud init
Welcome! This command will take you through the configuration of gcloud.
Run Code Online (Sandbox Code Playgroud)

然后它将询问您一系列问题:

  • 当它要求您选择要使用的配置时,请选择[1] Re-initialize this configuration [testconfig] with new settings
  • 然后,它将要求您选择或登录帐户。
  • 然后它将要求您选择或创建一个项目。
  • 最后,它将询问您是否要为项目设置默认区域。由你决定; 对于所有项目都在同一区域中的项目,请继续进行设置。

 

Your Google Cloud SDK is configured and ready to use!
Run Code Online (Sandbox Code Playgroud)

使用切换帐户gcloud config configurations activate [config name]