Search code examples
google-cloud-platformterraformgoogle-secret-manager

How can I give a service account access to a particular secret?


I want to grant a service account access to a secret in Google Secrets Manager.

I can access the secret like this:

gcloud beta secrets versions access 1 --secret="thesecret" --project="myproject"

But when my service account tries the same command, gcloud emits this error:

ERROR: (gcloud.beta.secrets.versions.access) PERMISSION_DENIED: Request had insufficient authentication scopes.

The main question is: What else do I need to do to ensure that the service account can access the secret?


I have granted that service account "roles/secretmanager.secretAccessor" in Terraform like this:

resource google_project_iam_binding the-binding {
  project = myproject
  role = "roles/secretmanager.secretAccessor"
  members = [
    "serviceAccount:theserviceaccount@someotherproject.iam.gserviceaccount.com",
  ]
}

And I can verify that it has that role both in the gcp console and like this:

gcloud projects get-iam-policy myproject  \
--flatten="bindings[].members" \                         
--format='table(bindings.role)' \
--filter="bindings.members:theserviceaccount@someotherproject.iam.gserviceaccount.com"

    ROLE
    roles/secretmanager.secretAccessor

But there's this concept from the docs:

If a member only needs to access a single secret's value, don't grant that member the ability to access all secrets. For example, you can grant a service account the Secret Accessor role (roles/secretmanager.secretAccessor) on a single secret.

So it's like an iam-policy-binding can have an affinity to a particular secret, but I'm not sure which gcloud commands or terraform resources I can use to create such an affinity.


Solution

  • The first problem is that I was mistaken about which service account my environment was configured to use. So I had granted access to the service account, but I wasn't using it after all (apparently they're initialized inconsistently in my case). I fixed that by running this command before trying to access the secret:

    gcloud config set account theserviceaccount@someotherproject.iam.gserviceaccount.com
    

    Also, I didn't realize that there were more than one toplevel gcloud command that let you modify iam policy bindings. I had been exploring gcloud iam ... when what I needed was:

    gcloud beta secrets add-iam-policy-binding projects/myproject/secrets/mysecret --member serviceAccount:theserviceaccount@someotherproject.iam.gserviceaccount.com --role roles/secretmanager.secretAccessor