1

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?

1 Answer 1

5

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.

3
  • But since service account is tightly coupled to a particular project would it be safe to extract it manually just as parsing json?
    – Some Name
    Feb 5, 2020 at 17:34
  • 1
    @SomeName - A service account in one project can be used in another project. You can also create a service account that cannot be used in the same project. The CLI supports switching service accounts, so automatically changing the default Project ID is not necessarily a good idea. The service accounts project_id key only means that project the service account was created in and has little to do with which projects the service account is authorized for. Feb 5, 2020 at 18:13
  • 1
    Right - I wouldn't stress a Service Account as "coupled" to a project. Even though a Service Account was created in a project, it still may have 0 access to anything in that project! IAM is a separate concern from where a Service Account was birthed. Feb 5, 2020 at 18:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.