How can curl authenticate to Google Cloud based on local gcloud's CLI authentication?

限于喜欢 提交于 2020-01-24 00:36:08

问题


My script uses a sequence of gcloud commands and of course gcloud is authenticated. I need to use curl to access GCP REST APIs that are not available to gcloud. I can do this by generating a JSON credentials file in the Cloud Console, but I'd rather not do that as a separate manual step.

This is how I do it now, using a JSON file downloaded from the Console.

    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

[Edit: The answer is to replace the gcloud auth string in that curl command. See answer below.) Without that downloaded JSON, I get this:

 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"
      }
    }

How can I leverage my gcloud authentication to use curl? I don't mind using the JSON if I can automate its generation as part of this script. For example, is there a way to call gcloud to generate this JSON, which I would then set as GOOGLE_APPLICATION_CREDENTIALS?


回答1:


Once you have the Cloud SDK authenticated, you can use the gcloud auth print-access-token command to get an access token for the current active account, without the need of specifying the path to the JSON credentials file.

You will still need the credentials.json file, if you wish to activate a service account for the Cloud SDK instance. However, I am pretty sure you will only have to do that once.

EDIT:

I noticed you are using the gcloud auth application-default print-access-token.

Keep in mind that, contrary to the gcloud auth print-access-token command, it uses the current Application Default Credential (ADC), which has to be set by specifying the credentials.json file path with the GOOGLE_APPLICATION_CREDENTIALS env variable, or by using the gcloud auth application-default login command.



来源:https://stackoverflow.com/questions/59764257/how-can-curl-authenticate-to-google-cloud-based-on-local-gclouds-cli-authentica

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!