How to use GOOGLE_APPLICATION_CREDENTIALS with gcloud on a server?

Solution 1:

gcloud generally does not use GOOGLE_APPLICATION_CREDENTIALS environment variable. It only has some commands to facilitate setting up these application default credentials in gcloud auth application-default [login|revoke|print-access-token...].

By default gcloud stores its configuration in ${HOME}/.config/gcloud. It is possible to override that location by setting CLOUDSDK_CONFIG environment variable.

Also it is possible (though more tedious) to override most setting so that they do not need to be preconfigured via gcloud config set ... and/or gcloud auth activate-service-account. For each setting one can specify environment variable.

For example the equivalent command you tried to use service account key file would be:

$ CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE=/etc/my-service-account-4b4b6e63aaed.json \
    gcloud alpha pubsub topics publish testtopic hello

Note that this will still cache credentials in CLOUDSDK_CONFIG since it needs to cache access-token, so that it wont have to refresh it on each invocation.

For your use case best option in my view would be

  1. Set CLOUDSDK_CONFIG to some temp directory
  2. gcloud auth activate-service-account --key-file=...
  3. ... use gcloud to do your work ...
  4. Remove temp CLOUDSDK_CONFIG directory.

Solution 2:

1) Create a ServiceAccount in GCP IAM. Check the box to "Furnish a new private key", and select JSON as the file type.

2) Download the JSON file to your server, and type: gcloud auth activate-service-account --key-file serviceaccount.json

3) Verify credentials were applied by running gcloud auth list.