Skip to main content

Cloud and deployment · Intermediate · 18 min

Grant least-privilege access in Google Cloud with IAM roles and service accounts

By Padding · Updated 18 Nov 2026
Google Cloud · gcloud 594.0.1

You will give one Cloud Run service its own service account that can read exactly one Secret Manager secret, test that access by impersonation instead of a key, add a grant that expires on its own, and review who can reach the secret.

On this page

Most Google Cloud projects start with too much access. People get the Editor role because it makes errors go away, and workloads run as a default service account that may have Editor on the whole project. When one of those identities leaks, everything in the project leaks with it.

Least privilege means each identity gets the smallest role it needs, on the smallest resource that works, for only as long as it needs it. In this tutorial you apply that to one small, real case: a Cloud Run service called invoice-api that needs one database password from Secret Manager and nothing else. By the end it has its own service account, that account can read that one secret and no other, you have tested it without downloading a key, and a teammate's temporary access expires without anyone having to remember to remove it.

The commands assume the gcloud CLI is set up with a default project. If it is not, work through setting up the gcloud CLI with configurations and projects first.

This can cost money. Secret Manager bills for stored secret versions and for access operations, and Cloud Run bills for request time. A service that receives no requests scales to zero. Check cloud.google.com/secret-manager/pricing and cloud.google.com/run/pricing for current figures before you start. The last step deletes everything this tutorial creates.

Step 1 · Learn the four parts of a Google Cloud grant

Every grant in Google Cloud IAM answers three questions, and is stored in a fourth place:

  • Who — a principal. That is a Google Account (user:ada@example.com), a Google group (group:oncall@example.com), a service account (serviceAccount:NAME@PROJECT_ID.iam.gserviceaccount.com) or a federated identity from outside Google.
  • What — a role, which is a named bundle of permissions such as secretmanager.versions.access. There are three kinds. Basic roles (Owner, Editor, Viewer) cover almost every service and are far too broad for production. Predefined roles are written by Google for one job in one service, such as roles/secretmanager.secretAccessor. Custom roles hold exactly the permissions you list, at the cost of maintaining them yourself.
  • Where — the resource the grant sits on. Resources form a tree: an organisation at the top, then folders, then projects, then individual resources such as a secret or a bucket.
  • Stored in — the allow policy attached to that resource. An allow policy is a list of role bindings, each binding one role to one or more principals, optionally with a condition.

Two rules follow from the tree. First, grants flow downwards: a role granted on a folder applies to every project and resource inside it. Second, grants only add up. A resource's effective access is its own policy plus every ancestor's, so you cannot take away on a secret what was granted on the project. (Google Cloud also has separate deny policies, which are checked before allow policies, but they are outside this tutorial.)

That second rule is why the level matters so much. If you grant roles/secretmanager.secretAccessor on the project, the service can read every secret in it, including ones created next year.

Write down, for invoice-api, the answers before you run anything:

  • Who: a new service account, invoice-api-runtime
  • What: roles/secretmanager.secretAccessor
  • Where: the secret invoice-db-password, not the project

Check it worked

You have three lines written down (who, what, where), and the "where" names a single secret rather than the project. If your "what" is Owner, Editor or Viewer, change it before you continue.

Step 2 · Find the broad grants already in your project

Before adding anything, look at what is there. Set two shell variables that the rest of the tutorial uses. Replace your-project-id with your project's ID and europe-west1 with the region you use; readers serving users in Southern Africa can use africa-south1 (Johannesburg):

Bash
PROJECT_ID=your-project-id
REGION=europe-west1
gcloud config set project "$PROJECT_ID"

List every principal that holds a basic role on the project:

Bash
gcloud projects get-iam-policy "$PROJECT_ID" \
  --flatten="bindings[].members" \
  --filter="bindings.role=roles/owner OR bindings.role=roles/editor" \
  --format="table(bindings.role, bindings.members)"

--flatten turns each policy binding into one row per member, so the filter and table work on single principals.

Look for two things in the output. One is people with Editor who only deploy one service or read logs; each of those is a candidate for a predefined role instead. The other is a member ending in -compute@developer.gserviceaccount.com. That is the Compute Engine default service account. In older projects it was granted Editor automatically, and Cloud Run services that do not name a service account use the project's default one. Organisations created on or after 3 May 2024 block that automatic grant by default, so newer projects may not show it.

Do not remove anyone's role yet. Removing Editor from a default service account can break workloads that quietly depend on it. Make a list, and change each one after you know what it is used for.

Check it worked

The table prints at least one row (your own account, as Owner). You have a short list of any other Owner or Editor members and whether the Compute Engine default service account is among them.

Step 3 · Create the secret and a dedicated service account

Enable the APIs this tutorial uses. This can take a minute:

Bash
gcloud services enable run.googleapis.com secretmanager.googleapis.com cloudasset.googleapis.com

Create the secret. The prompt below hides what you type (stty -echo) and keeps the password out of your shell history and off the command line, and printf sends it to gcloud through standard input (--data-file=-). It works in both bash and zsh, the default shell on macOS:

Bash
printf 'Database password: '; stty -echo; read -r DB_PASSWORD; stty echo; echo
printf '%s' "$DB_PASSWORD" | gcloud secrets create invoice-db-password --data-file=-
unset DB_PASSWORD

Create a second secret that the service should never be able to read. You use it later to prove the boundary holds:

Bash
printf '%s' "not-for-invoice-api" | gcloud secrets create payroll-api-token --data-file=-

Now create the service account. Give it a name that says which workload it belongs to, so anyone reading a policy later knows what it is for:

Bash
gcloud iam service-accounts create invoice-api-runtime \
  --display-name="invoice-api runtime" \
  --description="Runs the invoice-api Cloud Run service. Reads invoice-db-password only."
SA_EMAIL="invoice-api-runtime@${PROJECT_ID}.iam.gserviceaccount.com"

A new service account has no roles at all. That is the starting point you want. Google notes that reads of a new account are eventually consistent, so if the next command says the account does not exist, wait a minute and try again.

Check it worked

Run gcloud iam service-accounts describe "$SA_EMAIL" --format="value(email, description)". It prints the email and the description you set. gcloud secrets list shows both invoice-db-password and payroll-api-token.

Step 4 · Grant one role on one secret

Bind the Secret Accessor role to the service account on the secret itself. Note the command: it is gcloud secrets add-iam-policy-binding, not gcloud projects add-iam-policy-binding. That one word is the difference between one secret and all of them:

Bash
gcloud secrets add-iam-policy-binding invoice-db-password \
  --member="serviceAccount:${SA_EMAIL}" \
  --role="roles/secretmanager.secretAccessor" \
  --condition=None

--condition=None says plainly that this binding has no condition. Secret Accessor reads secret values only. It cannot list secrets, change them, or change who has access, which are the Viewer, Secret Version Manager and Admin roles' jobs.

Now attach the account to the service. This deploys Google's small public sample container as invoice-api, runs it as invoice-api-runtime, and exposes the secret to it as the environment variable DB_PASSWORD. If you already have your own service from deploying a container to Cloud Run, use your image instead:

Bash
gcloud run deploy invoice-api \
  --image=us-docker.pkg.dev/cloudrun/container/hello \
  --region="$REGION" \
  --service-account="$SA_EMAIL" \
  --set-secrets="DB_PASSWORD=invoice-db-password:latest" \
  --no-allow-unauthenticated

To attach a service account to a Cloud Run service, the person deploying needs the iam.serviceAccounts.actAs permission on that account. As Owner you have it. When a teammate deploys, grant them the Service Account User role on this one service account, not on the project:

Bash
gcloud iam service-accounts add-iam-policy-binding "$SA_EMAIL" \
  --member="user:TEAMMATE_EMAIL" \
  --role="roles/iam.serviceAccountUser"

Replace TEAMMATE_EMAIL with their address, or skip that command if you deploy alone.

Check it worked

Print the secret's policy:

Bash
gcloud secrets get-iam-policy invoice-db-password --format=yaml

It has one binding for roles/secretmanager.secretAccessor with serviceAccount:invoice-api-runtime@... as its member. Run the same command for payroll-api-token: the service account does not appear there. Then confirm the service runs as the new account:

Bash
gcloud run services describe invoice-api --region="$REGION" \
  --format="value(spec.template.spec.serviceAccountName)"

It prints the invoice-api-runtime email, not a -compute@developer.gserviceaccount.com address.

Step 5 · Test the account by impersonation, not with a key

You want to see the world as invoice-api-runtime sees it. The old way was to create a JSON key for the service account and log in with it. Do not do that. A key is a long-lived password in a file. It gets copied to laptops, pasted into CI settings and committed to repositories, and it works for anyone who finds it until someone deletes it. Organisations created on or after 3 May 2024 block key creation by default for that reason.

Impersonation gives you a short-lived token instead, issued only while your own account has permission. Grant yourself the Service Account Token Creator role on this one service account. Replace YOUR_EMAIL with the address you signed in to gcloud with:

Bash
gcloud iam service-accounts add-iam-policy-binding "$SA_EMAIL" \
  --member="user:YOUR_EMAIL" \
  --role="roles/iam.serviceAccountTokenCreator"

IAM changes can take a few minutes to apply. Then read the allowed secret as the service account. The output goes to wc -c, so you see how many characters came back, not the password itself:

Bash
gcloud secrets versions access latest --secret=invoice-db-password \
  --impersonate-service-account="$SA_EMAIL" | wc -c

Now try what the account should not be able to do:

Bash
gcloud secrets versions access latest --secret=payroll-api-token \
  --impersonate-service-account="$SA_EMAIL"
gcloud secrets list --impersonate-service-account="$SA_EMAIL"

Both should fail with a permission denied error. The first is a different secret; the second needs a list permission on the project, which the account was never given.

Finally, confirm that nobody has made a key for this account behind your back:

Bash
gcloud iam service-accounts keys list --iam-account="$SA_EMAIL" --managed-by=user

Check it worked

The first command prints a number equal to the length of your password, and gcloud warns that it is impersonating the service account. Both "should fail" commands end in a permission error rather than output. The keys list prints nothing, because there are no user-managed keys.

Step 6 · Give a teammate access that expires on its own

Next week an on-call engineer needs to rotate the database password: add a new version of the secret, then disable the old one. That is the Secret Version Manager role. They need it for a week, not for ever.

Add the grant with an IAM condition that compares the request time to a deadline. Replace ONCALL_EMAIL with their address and the date with one about seven days from now, in UTC:

Bash
gcloud secrets add-iam-policy-binding invoice-db-password \
  --member="user:ONCALL_EMAIL" \
  --role="roles/secretmanager.secretVersionManager" \
  --condition='expression=request.time < timestamp("2026-12-02T00:00:00Z"),title=rotation-until-2026-12-02,description=Password rotation, on-call week'

After the deadline, the binding still sits in the policy, but it no longer grants anything. Keep three limits in mind:

  • You cannot put a condition on Owner, Editor or Viewer, or on grants to allUsers. That is one more reason to use predefined roles.
  • A condition does not narrow an existing grant. If the engineer already holds the same role without a condition, on the secret or higher up, the deadline changes nothing. Check the project policy for them first.
  • Expired bindings pile up. Remove them during your regular access review.

If your team works across time zones, write the deadline in UTC as shown and tell the engineer the local time it ends, so access does not stop in the middle of their working day.

Check it worked

Run gcloud secrets get-iam-policy invoice-db-password --format=yaml. The new binding has a condition block containing your title, rotation-until-2026-12-02, and the request.time < timestamp(...) expression. The service account's binding from earlier has no condition.

Step 7 · Review who can reach the secret

A policy on one resource only tells part of the story, because access also arrives from folders, the organisation and groups. Policy Analyzer answers the full question. It needs the Cloud Asset API (enabled earlier) and the Cloud Asset Viewer role, which Owner includes.

Ask which resources the service account can read secret values from:

Bash
gcloud asset analyze-iam-policy --project="$PROJECT_ID" \
  --identity="serviceAccount:${SA_EMAIL}" \
  --permissions="secretmanager.versions.access"

Then ask the reverse question for your own account, which is a quick way to see how much an Owner can actually do:

Bash
gcloud asset analyze-iam-policy --project="$PROJECT_ID" \
  --identity="user:YOUR_EMAIL" \
  --permissions="secretmanager.versions.access" \
  --expand-resources

The same queries are available in the console under IAM & Admin, then Policy analyzer, which is handy when you share findings with someone who does not use the CLI. Results are a starting point for a human decision. Read each row and ask whether that principal still needs that access before you change anything.

Check it worked

The first query lists exactly one resource, the invoice-db-password secret, reached through the roles/secretmanager.secretAccessor binding. payroll-api-token is not in it. The --expand-resources flag makes the second query list the resources under the project as well as the project itself, so you see something like both secrets for your account, reached through the project-level roles/owner binding. If the first query lists more than one secret, look for a project or folder grant to the service account and remove it.

Step 8 · Remove what you created

Delete everything in reverse order. Deleting the service, secrets and service account removes their policies with them, including your Token Creator grant on the service account:

Bash
gcloud run services delete invoice-api --region="$REGION"
gcloud secrets delete invoice-db-password
gcloud secrets delete payroll-api-token
gcloud iam service-accounts delete "$SA_EMAIL"

Each delete asks you to confirm. If you granted a teammate Service Account User earlier, that grant also sits on the service account's own policy, so it goes with it.

Keep the habit, not the demo. For each workload in your real projects: one service account named after it, predefined roles only, granted on the resource it touches, no keys, and time-limited grants for people.

Check it worked

gcloud run services list --region="$REGION" no longer shows invoice-api, gcloud secrets list shows neither secret, and gcloud iam service-accounts list does not include invoice-api-runtime.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.