如何获取活动的已认证gcloud账户?

54

使用 gcloud auth ... 命令,您可以添加或删除在 gcloud 命令期间使用的帐户。

有没有一种方法可以不使用 grepawk 来获取活动帐户?

gcloud auth list 对人类很好,但对机器不够简洁。我需要一个更简洁的解决方案。

gcloud config list account 同样向我显示了冗长的输出:

Your active configuration is: [default]

[core]
account = service@<my_project>.iam.gserviceaccount.com

类似问题:https://dev59.com/cZPfa4cB1Zd3GeqPGrEw - cherba
5个回答

65

我找到了解决方案:

gcloud config list account --format "value(core.account)"

这会告诉您:

Your active configuration is: [default]

service@<my_project>.iam.gserviceaccount.com
为了避免“活动配置消息”,您可以将stderr重定向到/dev/null
$ gcloud config list account --format "value(core.account)" 2> /dev/null
service@<my_project>.iam.gserviceaccount.com

如果--verbosity在这种情况下也起作用并删除info消息,那将是很好的。这意味着:

$ gcloud config list account --format "value(core.account)" --verbosity error

有谷歌员工在吗?如果这是一个合理的功能/错误请求/报告,请发表评论。


6
您可以选择使用 gcloud auth list --filter=status:ACTIVE --format="value(account)"。详见 https://cloud.google.com/sdk/gcloud/reference/auth/list。 - Luís Bianchin
1
我一直遇到核心/帐户未始终设置的问题。Luís Bianchin的替代方法是直接检查授权列表,这被证明更可靠。它还有一个额外的好处,如果没有找到任何内容,它不会打印新行字符。 - Alex Jansen

29

这似乎也有效

gcloud config get-value account

9

以下两个命令将得到相同的结果:

$ gcloud config get-value account
$ gcloud config list --format 'value(core.account)'

但是,如果您想将帐户设置为可以在外部激活,则可以使用JSON密钥完成:

#!/bin/bash
if [[ ! $(gcloud config get-value account &> /dev/null) ]]
then
    GCP_SA_KEY=<json credential key>
    GCP_ACCOUNT=service@<my_project>.iam.gserviceaccount.com 
    if [ -z $GOOGLE_APPLICATION_CREDENTIALS ]
    then
        echo $GCP_SA_KEY > google-app-creds.json
        export GOOGLE_APPLICATION_CREDENTIALS=$(realpath google-app-creds.json)
        gcloud auth activate-service-account $GCP_ACCOUNT --project=<my_project> \
        --key-file=$GOOGLE_APPLICATION_CREDENTIALS
    fi
fi

输出将会是这样的
$ bash /path/to/the/above/file
Activated service account credentials for: [service@<my_project>.iam.gserviceaccount.com] 

To take a quick anonymous survey, run: 
  $ gcloud alpha survey

$ gcloud config get-value account
service@<my_project>.iam.gserviceaccount.com

2
对于那些想要检查是否存在活动账户的人,请注意这两个命令的输出有微小的差异:gcloud config get-value account将返回(unset),而gcloud config list --format 'value(core.account)'将返回一个空输出。 - Knak

2

打开 gcloud 控制台,然后运行以下命令,这对我很有效:gcloud auth list


原始问题陈述:“gcloud auth list 对人类来说很好,但对机器来说不够好。我想要一个更干净的解决方案。” - Kirby

0

gcloud 命令通常是为人类消费而设计的,而不是机器。

你想做什么?一般来说,如果您需要程序化身份验证,您将使用 应用程序默认凭据 和(例如)GOOGLE_APPLICATION_CREDENTIALS 环境变量,客户端库 从中获取身份验证信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接