GCP IAM least privilege in practice: groups, roles, service accounts

How I structure Google Cloud IAM so people get access through groups, workloads get one keyless service account each, and every grant is small and auditable.

Published

Updated

Reading time

9 min

The target state is short to describe. People reach Google Cloud through groups, each group holds the smallest predefined role on the smallest resource that works, every workload runs as its own service account, and nobody holds a downloaded key. The rest of this article builds that state in order, using a hypothetical starting point: a project where access was granted one request at a time, so it has a few dozen individual email addresses, some with Editor, and every service running as the default Compute Engine service account.

Every command below uses gcloud; replace ORG_ID, folder IDs, project IDs and example.com with your own values.

How a grant reaches a resource#

Two facts drive every later decision. First, the resource hierarchy: organization, folders, projects, then resources such as buckets, secrets and services. An allow policy set at any level is inherited by everything beneath it, and the effective policy on a resource is the union of its own policy and all of its ancestors'. Second, allow policies are purely additive. You cannot use an allow policy on a project to take away a role granted on its folder. Only IAM deny policies subtract, and they are a separate mechanism.

A grant high in the tree is therefore a grant everywhere below it, including projects that do not exist yet. Least privilege in GCP is mostly the discipline of granting low.

Policies flow down the tree. Grants land as low as possible: groups on folders, workloads on individual resources.

Give production its own folder#

Folders are the cheapest security control available. With production in its own folder, a production-wide grant or org policy covers every production project, including future ones, and cannot leak into development.

terminalbash
gcloud resource-manager folders create --display-name="prod" --organization=ORG_ID
gcloud resource-manager folders create --display-name="non-prod" --organization=ORG_ID
 
gcloud projects create app-prod --folder=PROD_FOLDER_ID
gcloud projects create app-staging --folder=NONPROD_FOLDER_ID

Split projects by environment and by trust boundary. A service that holds payment data deserves a project where not everybody can read.

Move people onto groups#

Create groups that describe jobs: platform-admins@, engineers@, oncall@, billing-viewers@. Cloud Identity Free can host them if you do not use Google Workspace. Membership lives in the directory and IAM only ever sees the group.

terminalbash
# Group creation and membership (Cloud Identity); the admin console works too.
# --organization takes the numeric organization ID or the primary domain.
gcloud identity groups create engineers@example.com \
  --organization=ORG_ID --display-name="Engineers"
gcloud identity groups memberships add \
  --group-email=engineers@example.com --member-email=alice@example.com
 
# Bind predefined roles to the group at the folder level
for role in roles/run.viewer roles/logging.viewer roles/monitoring.viewer; do
  gcloud resource-manager folders add-iam-policy-binding NONPROD_FOLDER_ID \
    --member="group:engineers@example.com" --role="$role"
done

Offboarding becomes one membership removal, and "who has access to staging?" becomes "who is in these three groups?", a question the directory already answers. The catch is that a binding to engineers@ is only as tight as the group's membership, so review group owners with the same care as IAM policies.

Choose roles by reading them#

Basic roles are the trap to avoid. roles/editor carries thousands of permissions across nearly every service, which is why it belongs in throwaway sandboxes only.

Role typeExampleUse it forCost of using it
Basicroles/editorThrowaway sandboxesThousands of permissions across nearly every service
Predefinedroles/run.developer, roles/secretmanager.secretAccessorThe default choiceOccasionally broader than a job needs
Customprojects/app-prod/roles/appDeployerWhen no predefined role is close enoughYou maintain it; new permissions are not added for you

Before granting a predefined role, read what it contains:

terminalbash
gcloud iam roles describe roles/run.developer --format="yaml(includedPermissions)"

If the closest predefined role is still too broad and the gap matters, write a custom role. A CI deployer for Cloud Run needs to update services and read revisions, not delete services or change IAM:

terminalbash
gcloud iam roles create appDeployer --project=app-prod \
  --title="App deployer" \
  --description="Deploy new revisions to existing Cloud Run services" \
  --stage=GA \
  --permissions=run.services.get,run.services.update,run.revisions.get,run.revisions.list,run.operations.get

Custom roles can be defined at the organization or project level, not on folders. They also do not evolve when Google adds permissions to a product: when a workflow needs a new permission, the custom role starts returning 403 until somebody edits it. Keep the number small and keep them in code.

Give each workload its own identity#

Every Cloud Run service, job, function and pipeline gets a service account named after the workload. The runtime identity of the api service is not the identity that deploys it, and neither is the identity of the nightly export job. Separate accounts also make every log line say which workload acted.

terminalbash
gcloud iam service-accounts create api-runtime --project=app-prod \
  --display-name="Runtime identity for the api service"
 
gcloud run deploy api --project=app-prod --region=europe-west1 \
  --image=europe-west1-docker.pkg.dev/app-prod/containers/api:1.42.0 \
  --service-account=api-runtime@app-prod.iam.gserviceaccount.com

Stop relying on default service accounts. Older organizations automatically granted Editor to the Compute Engine default service account. The org policy constraint iam.automaticIamGrantsForDefaultServiceAccounts prevents that, and the managed constraint iam.managed.preventPrivilegedBasicRolesForDefaultServiceAccounts blocks granting it later by hand. To retire an existing default account, create the dedicated one, move the workload, then remove the grant, in that order.

The escalation path hidden in "act as"#

Anyone who can act as a service account inherits its permissions, and roles/iam.serviceAccountUser granted at project level lets the holder act as every service account in that project. Grant it on the specific account instead:

terminalbash
gcloud iam service-accounts add-iam-policy-binding \
  api-runtime@app-prod.iam.gserviceaccount.com \
  --member="serviceAccount:ci-deployer@app-prod.iam.gserviceaccount.com" \
  --role="roles/iam.serviceAccountUser"

Take the keys away#

A JSON key is a long-lived bearer credential in a file, and it does not expire by default. Nearly every workload has a keyless alternative: attached service accounts on Google Cloud, Workload Identity Federation for CI and other clouds (the GitHub Actions setup is in its own article), and impersonation for people on laptops.

Make the rule structural with an organization policy. Organizations created on or after 3 May 2024 enforce the key creation and upload blocks by default; older ones should enable them explicitly:

disable-sa-keys.yamlyaml
name: organizations/ORG_ID/policies/iam.managed.disableServiceAccountKeyCreation
spec:
  rules:
    - enforce: true
terminalbash
gcloud org-policies set-policy disable-sa-keys.yaml

If a vendor truly requires a key, override the constraint on that single project and record why.

Bind sensitive resources directly#

Granting roles/secretmanager.secretAccessor on a project lets the holder read every secret in it, including ones created next year. Bind on the secret instead, and do the same for buckets. How the service then reads the secret is covered in configuration and secrets for multi-service Node apps.

terminalbash
gcloud secrets add-iam-policy-binding db-password --project=app-prod \
  --member="serviceAccount:api-runtime@app-prod.iam.gserviceaccount.com" \
  --role="roles/secretmanager.secretAccessor"
 
gcloud storage buckets add-iam-policy-binding gs://app-prod-exports \
  --member="serviceAccount:nightly-export@app-prod.iam.gserviceaccount.com" \
  --role="roles/storage.objectCreator"

The api service can read one secret. The export job can write objects to one bucket but cannot read or delete them. If either is compromised, the damage stops there. The price is visibility: a secret-level binding does not appear in gcloud projects get-iam-policy, so anyone auditing only project policies will miss it.

Let elevated access expire#

Standing admin access hurts most when an account is phished. IAM conditions let a binding carry an expiry:

terminalbash
gcloud projects add-iam-policy-binding app-prod \
  --member="group:oncall@example.com" \
  --role="roles/run.admin" \
  --condition='expression=request.time < timestamp("2026-10-07T18:00:00Z"),title=incident-4711,description=Expires at end of incident window'

After the timestamp the binding stays in the policy but grants nothing; remove it in the next Terraform run. For a managed just-in-time flow with approvals and justification, look at Privileged Access Manager, which grants and revokes these bindings for you.

Put it in Terraform without locking yourself out#

Every grant above belongs in code, reviewed like any other change. The Google provider offers three flavours per resource type, and the difference is the most common way teams lock themselves out:

  • google_*_iam_member adds one member to one role and leaves everything else alone. Use this.
  • google_*_iam_binding owns the full member list for one role. Anything added outside Terraform is removed on the next apply.
  • google_*_iam_policy owns the entire policy. A mistake in it removes every other grant, including the ones that would let you repair it.
iam.tfhcl
resource "google_service_account" "api_runtime" {
  project      = var.project_id
  account_id   = "api-runtime"
  display_name = "Runtime identity for the api service"
}
 
resource "google_secret_manager_secret_iam_member" "api_db_password" {
  project   = var.project_id
  secret_id = google_secret_manager_secret.db_password.secret_id
  role      = "roles/secretmanager.secretAccessor"
  member    = "serviceAccount:${google_service_account.api_runtime.email}"
}
 
resource "google_folder_iam_member" "engineers_nonprod" {
  for_each = toset([
    "roles/run.viewer",
    "roles/logging.viewer",
    "roles/monitoring.viewer",
  ])
  folder = "folders/${var.nonprod_folder_id}"
  role   = each.value
  member = "group:engineers@example.com"
}
 
resource "google_project_iam_member" "oncall_breakglass" {
  project = var.project_id
  role    = "roles/run.admin"
  member  = "group:oncall@example.com"
 
  condition {
    title       = "incident-4711"
    description = "Expires at end of incident window"
    expression  = "request.time < timestamp(\"2026-10-07T18:00:00Z\")"
  }
}

Use _member resources and keep an out-of-band break-glass group at the organization level. The Terraform runner should authenticate through federation too, with a service account that holds only the IAM admin roles it needs on the folders it manages.

Check the result, and keep checking#

Start with one project's policy, flattened to one member and one role per row:

terminalbash
gcloud projects get-iam-policy app-prod \
  --flatten="bindings[].members" \
  --format="table(bindings.role, bindings.members, bindings.condition.title)"

That shows direct grants only. For the whole organization, including inherited and resource-level bindings, use Cloud Asset Inventory:

terminalbash
# Every place a basic Owner role is granted
gcloud asset search-all-iam-policies --scope=organizations/ORG_ID \
  --query='policy:roles/owner'
 
# Every binding that names an individual user instead of a group
gcloud asset search-all-iam-policies --scope=organizations/ORG_ID \
  --query='memberTypes:user'
 
# Who can read secret values in app-prod, through any path
gcloud asset analyze-iam-policy --organization=ORG_ID \
  --full-resource-name="//cloudresourcemanager.googleapis.com/projects/app-prod" \
  --permissions="secretmanager.versions.access"

The last command is Policy Analyzer. It expands groups and inheritance, so it answers "who can read the production database password?" directly. The IAM recommender observes up to 90 days of permission usage and suggests removals or smaller roles:

terminalbash
gcloud recommender recommendations list --project=app-prod \
  --location=global --recommender=google.iam.policy.Recommender \
  --format="table(description, stateInfo.state)"

To watch changes as they happen, every SetIamPolicy call is recorded in Admin Activity audit logs, which are always on:

terminalbash
gcloud logging read 'protoPayload.methodName="SetIamPolicy"' \
  --project=app-prod --freshness=30d \
  --format="table(timestamp, protoPayload.authenticationInfo.principalEmail, protoPayload.resourceName)"

Route that filter to a log-based alert so a grant made outside Terraform pages someone the same day. The full quarterly procedure, with snapshots and a diff, is in auditing a GCP IAM policy.

CostWhere the money goes

IAM, groups, conditions and org policies are free, and Admin Activity audit logs are free and always on. Data Access audit logs, which record who read data, are off by default for most services and are billed as Cloud Logging ingestion beyond a free allotment; see the Cloud Logging pricing page. Enable them selectively, for example on Secret Manager in production. Per the role recommendations overview, basic-role recommendations are free at every level, while recommendations for predefined roles and resource-level grants require Security Command Center Premium or Enterprise.

What still goes wrong after the restructure#

  • Propagation is not instant. Grants and revocations usually take effect within minutes, occasionally longer. Do not write automation that grants a role and uses it in the same second, and do not assume a revocation is effective the moment the command returns.
  • Additive inheritance surprises people. Removing a role from a project does nothing if the same principal holds it on the folder. Check ancestors, which is exactly what Policy Analyzer does.
  • More identities means more to name. One service account per workload produces dozens of accounts. Without Terraform and a naming convention that becomes its own mess.

Where to stop#

For a personal sandbox that holds no real data, one project with your own account as Owner and a billing budget is enough, though the one rule that costs nothing still applies: do not download service account keys. If your organization already runs a central landing zone, do not build a parallel hierarchy. Fit your projects into its folders and groups, and spend your effort on the resource-level grants and workload identities that a platform team cannot see from above.

Share
All articles →

A one-hour audit procedure for Google Cloud IAM: snapshot the policies, run eight targeted queries, triage what you find, and keep the result diffable.

13 min