Why does exporting GOOGLE_APPLICATION_CREDENTIALS

2019-06-06 07:03发布

问题:

The google docs say to export the env var GOOGLE_APPLICATION_CREDENTIALS with the path to a service account's JSON key, and gcloud will use it. I can't get it to work.

My command is:

GOOGLE_APPLICATION_CREDENTIALS=/home/ubuntu/.config/google-creds.json bq ls

This just brings up an error:

You do not currently have an active account selected. Please run:

$ gcloud auth login

to obtain new credentials, or if you have already logged in with a different account:

$ gcloud config set account ACCOUNT

to select an already authenticated account to use.

gcloud -v gives:

Google Cloud SDK 92.0.0

bq 2.0.18
bq-nix 2.0.18
core 2016.01.12
core-nix 2015.11.24
gcloud
gsutil 4.16
gsutil-nix 4.15

What am I doing wrong, and how can I fix this? I need gsutil and bq to use this file. I'm working with multiple projects so can't activate any one in particular.

回答1:

Have you tried gcloud auth activate-service-account?:

gcloud auth activate-service-account --key-file google-creds.json

(It seems the command-line tools don't go down the whole credential discovery chain, as gcloud does when it's being used as a library in code.)


If you have several configurations (eg auth, project ids) that you need to use, you can set up configurations. For example, if you have two service account credentials you'd like to use - call them sa1.json and sa2.json - you can do something like:

$ gcloud config configurations create proj1
$ gcloud config configurations activate proj1
$ gcloud auth activate-service-account --key-file sa1.json

$ gcloud config configurations create proj2
$ gcloud config configurations activate proj2
$ gcloud auth activate-service-account --key-file sa2.json

Now, you can either use the gcloud config configurations activate command to set the configuration you'd like to use, or set the CLOUDSDK_ACTIVE_CONFIG_NAME environment variable to specify under which configuration you'd like to run a command. ie to run bq ls using the sa1.json cred:

$ CLOUDSDK_ACTIVE_CONFIG_NAME=proj1 bq ls

and for the sa2.json cred:

$ CLOUDSDK_ACTIVE_CONFIG_NAME=proj2 bq ls