Warm tip: This article is reproduced from stackoverflow.com, please click
bash gcloud google-cloud-platform service-accounts

Is it possible to avoid setting project_id explicitly when authing with service account?

发布于 2020-04-20 11:26:57

I'm trying to authenticate in a bash script and enable my service account and I have cred.json. Here is what I tried:

gcloud auth activate-service-account --key-file=/etc/gcp-cred.json

The problem is that I have to set project explicitly:

gcloud config set project my_proj

Which is kind of redundant because gcp-cred.json contains this project already as a field:

"project_id": "my_proj"

Is there a way to avoid doing gcloud config set project explicitly and set it with gcp-cred.json?

Questioner
Some Name
Viewed
32
Thomas Ruble 2020-02-06 01:19

No -- gcloud will not change your working core project when authenticating.

The trick here is that authenticating & setting your "default" working project for gcloud are separate concerns. You can set your project without authenticating, and you can authenticate without changing your project.

The logic here stems from the fact that an identity can have access to many projects. Even though a Service Account is homed to a particular project, it could very well be authorized to access any other project. So, the gcloud program makes no assumptions about which project you want your Service Account to act on.

Secondarily, in general you do not have to set your default working project for gcloud -- you can specify the project that is the target of your action with the flag --project PROJECT_ID. See docs for that gcloud flag here.