Jos*_*Fox 8 authentication curl google-cloud-platform gcloud
我的脚本使用一系列gcloud命令,当然 gcloud 已经过身份验证。我需要使用curl来访问gcloud无法使用的GCP REST API。我可以通过在 Cloud Console 中生成 JSON 凭据文件来完成此操作,但我不想将其作为单独的手动步骤来执行。
[编辑:答案是将gcloud authcurl命令中的字符串替换为gcloud auth print-access-token. 请参阅下面的答案。]
这就是我现在的做法,使用从控制台下载的 JSON 文件。
GOOGLE_APPLICATION_CREDENTIALS=credentials.json
curl -X POST -H "Authorization: Bearer \"$(gcloud auth application-default print-access-token)\"" \
-H "Content-Type: application/json; charset=utf-8" \
https://cloudresourcemanager.googleapis.com/v1/projects/<MY_PROJECT>:getAncestry
Run Code Online (Sandbox Code Playgroud)
如果没有下载的 JSON,我会得到以下结果:
ERROR: (gcloud.auth.application-default.print-access-token)
The Application Default Credentials are not available. They are available if running in Google Compute Engine.
Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing
to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials
for more information.
{ "error": {
"code": 401,
"message": "Request had invalid authentication credentials.
Expected OAuth 2 access token, login cookie or other valid authentication credential.
See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
Run Code Online (Sandbox Code Playgroud)
如何利用我的gcloud身份验证来使用curl?如果我可以自动生成 JSON 作为此脚本的一部分,我不介意使用 JSON。例如,有没有一种方法可以调用gcloud来生成此 JSON,然后我将其设置为GOOGLE_APPLICATION_CREDENTIALS?
对 Cloud SDK 进行身份验证后,您可以使用gcloud auth print-access-token命令获取当前活动帐户的访问令牌,而无需指定 JSON 凭证文件的路径。
如果您希望激活 Cloud SDK 实例的服务帐户,您仍然需要credentials.json 文件。不过,我很确定您只需这样做一次。
编辑:
我注意到你正在使用gcloud auth application-default print-access-token.
请记住,与该gcloud auth print-access-token命令相反,它使用当前的应用程序默认凭据 (ADC),必须通过使用 GOOGLE_APPLICATION_CREDENTIALS env 变量指定凭据.json 文件路径或使用 gcloud auth application-default login来设置该凭据命令。
| 归档时间: |
|
| 查看次数: |
14235 次 |
| 最近记录: |