Keyless CI/CD: Workload Identity Federation for GitHub Actions
Swap service account keys in GitHub secrets for short-lived OIDC tokens, lock the trust to your own repo, and deploy to Cloud Run with no JSON key.
A deploy workflow that authenticates with a secret named GCP_SA_KEY holds a service account JSON key. That key has no expiry, does not know it is supposed to be used from a GitHub runner on main, and works equally well from a laptop in another country. Anyone who extracts it from a compromised dependency or a careless echo in a log has the same power as your pipeline for as long as the key exists. Rotating it means creating a new key, updating every repository that uses it and deleting the old one without breaking a release, which is why it rarely happens. Google's own guidance on service account keys is to avoid them where you can.
Workload Identity Federation (WIF) removes the stored secret. GitHub issues every workflow job a signed OpenID Connect token that says which repository, branch, environment and workflow it came from. Google Cloud can trust that issuer, check the claims and hand back a short-lived credential. This article sets that up with gcloud, locks the trust to one organization and then one repository, deploys to Cloud Run, and covers the errors you will meet on the way. Commands assume a project my-project, a GitHub organization acme and a repository acme/api. I did this for the deploy pipelines of a large-scale social platform I'm building, and it was an afternoon of setup for what was one of the better security returns on the whole project.
What the two sides exchange#
- The job, running with
permissions: id-token: write, asks GitHub's OIDC endpoint for a JWT. The issuer ishttps://token.actions.githubusercontent.comand the claims includesub,repository,repository_owner,repository_id,ref,environmentandworkflow_ref, listed in GitHub's OIDC documentation. - The
google-github-actions/authaction sends that JWT to Google's Security Token Service (STS). - STS finds the workload identity pool provider, verifies the signature against GitHub's published keys, applies your attribute mapping and evaluates your attribute condition. If the condition fails, the exchange is rejected there.
- STS returns a federated token. With impersonation, the action then asks the IAM Credentials API for an access token for your service account, which succeeds only if the federated identity holds
roles/iam.workloadIdentityUseron that account. - Later
gcloudcalls and client libraries use the short-lived token.
There are two gates. The provider's attribute condition decides which GitHub tokens are accepted at all. The IAM binding decides which of those identities may become which service account. You want both.
You can skip the service account and grant roles directly to the federated principal, but not every Google Cloud product supports federated principals, and a Cloud Run deploy needs to act as the runtime service account anyway. I use impersonation because every tool understands it and the audit trail names the account.
Enable the APIs and create a pool#
gcloud services enable \
iam.googleapis.com \
iamcredentials.googleapis.com \
sts.googleapis.com \
run.googleapis.com \
artifactregistry.googleapis.com \
--project=my-projectA forgotten iamcredentials.googleapis.com is a common reason for a first run to fail.
A pool is a container for external identities. I create one per trust domain (one for GitHub, another for any other CI system) rather than one per repository.
gcloud iam workload-identity-pools create github \
--project=my-project \
--location=global \
--display-name="GitHub Actions"Create the provider and its condition#
This step decides the security of the whole setup.
gcloud iam workload-identity-pools providers create-oidc acme-github \
--project=my-project \
--location=global \
--workload-identity-pool=github \
--issuer-uri="https://token.actions.githubusercontent.com" \
--attribute-mapping="\
google.subject=assertion.sub,\
attribute.repository=assertion.repository,\
attribute.repository_owner=assertion.repository_owner,\
attribute.ref=assertion.ref" \
--attribute-condition="assertion.repository_owner == 'acme'"The attribute mapping translates GitHub claims into attributes IAM can reason about. google.subject is mandatory and appears in audit logs; the attribute.* keys are yours to define and are what principalSet bindings reference. Map only what you will use.
The attribute condition is a CEL expression evaluated on every exchange. It is not optional because GitHub's issuer is shared by every repository on github.com: the issuer URL is identical for your private monorepo and for a repository created five minutes ago by a stranger. Without a condition the provider accepts all of them, and the only barrier left is whether your IAM bindings happen to be tight. One overly broad principalSet and anyone on GitHub can deploy to your project. Google's deployment pipeline guidance requires a condition when the provider trusts GitHub's issuer.
repository_owner and repository are names. If an organization is renamed or deleted, someone else can register the old name. For high-value projects, map the immutable numeric claims instead, for example attribute.repository_owner_id=assertion.repository_owner_id, and use assertion.repository_owner_id == '123456' in the condition. Get the ID with gh api orgs/acme --jq .id.
If only two repositories should ever reach this project, say so:
gcloud iam workload-identity-pools providers update-oidc acme-github \
--project=my-project \
--location=global \
--workload-identity-pool=github \
--attribute-condition="assertion.repository_owner == 'acme' && assertion.repository in ['acme/api', 'acme/web']"Give the pipeline its own service account#
One account per deploy target keeps the blast radius small. In my setup the trust names specific repositories, one repository per service, and the deployer can push images and deploy services and nothing else. Reviewing those bindings took a proper audit pass, and it was tedious precisely because each binding is small and looks harmless on its own.
gcloud iam service-accounts create api-deployer \
--project=my-project \
--display-name="Deploys the api service from GitHub"
SA="api-deployer@my-project.iam.gserviceaccount.com"
# Deploy Cloud Run services and push images
gcloud projects add-iam-policy-binding my-project \
--member="serviceAccount:${SA}" --role="roles/run.developer"
gcloud projects add-iam-policy-binding my-project \
--member="serviceAccount:${SA}" --role="roles/artifactregistry.writer"
# Allow it to attach the runtime service account to the Cloud Run service
gcloud iam service-accounts add-iam-policy-binding \
api-runtime@my-project.iam.gserviceaccount.com \
--project=my-project \
--member="serviceAccount:${SA}" --role="roles/iam.serviceAccountUser"The last binding is scoped to the single runtime account. A project-level serviceAccountUser would let the deployer act as every service account in the project, which defeats the point. The reasoning behind per-workload accounts is in GCP IAM least privilege in practice.
Let one repository become that account#
Now allow tokens from one repository to impersonate api-deployer. This command needs the project number, not the ID:
PROJECT_NUMBER=$(gcloud projects describe my-project --format="value(projectNumber)")
gcloud iam service-accounts add-iam-policy-binding \
api-deployer@my-project.iam.gserviceaccount.com \
--project=my-project \
--role="roles/iam.workloadIdentityUser" \
--member="principalSet://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/github/attribute.repository/acme/api"The principalSet matches every federated identity whose mapped repository attribute equals acme/api. There are two principal formats worth knowing:
principalSet://…/attribute.<name>/<value>matches a group of identities by a mapped attribute.principal://…/subject/<subject>matches exactly onegoogle.subject, for examplerepo:acme/api:ref:refs/heads/main.
Write the workflow#
The actions are pinned to full commit SHAs, with the version in a comment. A deploy job that holds an identity token is exactly the job you do not want a moved tag to run in. The SHAs below correspond to the current majors at the time of writing (actions/checkout v7.0.1, google-github-actions/auth v3.0.0, setup-gcloud v3.0.1 and deploy-cloudrun v3); look them up again when you update.
name: deploy
on:
push:
branches: [main]
permissions:
contents: read
id-token: write
jobs:
deploy:
runs-on: ubuntu-latest
environment: production
env:
REGION: europe-west1
IMAGE: europe-west1-docker.pkg.dev/my-project/apps/api:${{ github.sha }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- id: auth
uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3.0.0
with:
workload_identity_provider: projects/123456789012/locations/global/workloadIdentityPools/github/providers/acme-github
service_account: api-deployer@my-project.iam.gserviceaccount.com
- uses: google-github-actions/setup-gcloud@aa5489c8933f4cc7a4f7d45035b3b1440c9c10db # v3.0.1
- name: Build and push
run: |
gcloud auth configure-docker europe-west1-docker.pkg.dev --quiet
docker build -t "$IMAGE" .
docker push "$IMAGE"
- uses: google-github-actions/deploy-cloudrun@2028e2d7d30a78c6910e0632e48dd561b064884d # v3
with:
service: api
region: ${{ env.REGION }}
image: ${{ env.IMAGE }}
flags: --service-account=api-runtime@my-project.iam.gserviceaccount.comid-token: write is what lets the job request the OIDC token at all, and setting permissions at workflow level drops every permission you do not list. The workload_identity_provider value is the full resource name with the project number; gcloud iam workload-identity-pools providers describe acme-github --location=global --workload-identity-pool=github --format="value(name)" prints it exactly. It is not a secret, so keep it in plain YAML or a repository variable.
The pipeline around it is deliberately dull: merging to a service's main branch builds the container, pushes it to Artifact Registry and rolls the service to the new revision. The one thing that bit me was not the identity at all but a cleanup policy on the registry. It deleted old artifacts by upload time, and a service that had not shipped for a while was running an image the policy considered old. The registry removed it. The service kept running, because the platform holds its own copy of a deployed image, until the next restart tried to pull it and could not. I fixed it by rebuilding the same tag, then changed the policy to respect recent use as well as age, and I now treat any tag that production references as something cleanup must never be able to delete.
Allow production only from a protected environment#
Repository-level trust is a start, but the usual requirement is that anyone can run CI and only main deploys to production. One quirk helps here. When a job references a GitHub environment, the sub claim changes from repo:acme/api:ref:refs/heads/main to repo:acme/api:environment:production. Environments carry protection rules (required reviewers, allowed branches) that GitHub enforces before the job starts, so bind the production service account to that exact subject:
# Only jobs running in the protected 'production' environment of acme/api
gcloud iam service-accounts add-iam-policy-binding \
api-deployer-prod@my-project.iam.gserviceaccount.com \
--project=my-project --role="roles/iam.workloadIdentityUser" \
--member="principal://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/github/subject/repo:acme/api:environment:production"This binding uses the raw subject, so the google.subject=assertion.sub mapping from the provider is all it needs; no extra attribute is mapped. Point the production workflow's service_account at api-deployer-prod and add a GitHub environment rule that only allows deployments from main. A pull request from a fork then has no route to the production account: it cannot enter the environment, so its token never carries the matching subject. For staging, a principalSet on the repository or a separate staging account is usually enough.
The migration trap is the other direction. Adding environment: to a job that used to authenticate by branch changes its subject, so any existing principal://…/subject/…ref… binding stops matching.
If staging and production live in separate Google Cloud projects, give each its own pool and provider. A mistake in the staging bindings then cannot grant anything in production, and the conditions stay short enough to read in review.
When the exchange fails#
The error messages are terse. These are the ones to expect and what they usually mean.
| Symptom | Likely cause | Fix |
|---|---|---|
Unable to get ACTIONS_ID_TOKEN_REQUEST_URL, or the auth step says OIDC is unavailable | Missing id-token: write, or a fork PR where GitHub withholds the token | Add the permission at workflow or job level; do not deploy from fork PRs |
The given credential is rejected by the attribute condition | The token's claims do not satisfy the CEL condition | Compare the condition with the actual claims; org-name casing and the environment vs ref subject are common culprits |
Permission 'iam.serviceAccounts.getAccessToken' denied | The workloadIdentityUser binding is missing, points at the wrong pool, or uses the project ID instead of the number | Re-check the principalSet string character by character |
invalid_target or "pool/provider does not exist" | Typo in workload_identity_provider, or the provider is disabled or deleted | Print the name with providers describe --format="value(name)" |
IAM Service Account Credentials API has not been used | API not enabled | Enable iamcredentials.googleapis.com |
| Works, then fails a minute after a change | IAM propagation | Wait a few minutes; IAM changes are eventually consistent |
Deploy step fails with iam.serviceaccounts.actAs denied | Deployer lacks serviceAccountUser on the runtime account | Grant it on that specific service account |
To see what GitHub actually put in the token, decode it inside a throwaway workflow on a non-production branch. You can fetch it with curl using ACTIONS_ID_TOKEN_REQUEST_URL and ACTIONS_ID_TOKEN_REQUEST_TOKEN and print only the payload claims. Never print the full token in a log, even a short-lived one.
Tie a revision back to a workflow run#
Keyless does not mean invisible. STS token exchanges appear in Cloud Audit Logs under sts.googleapis.com, and service account impersonation is logged by iamcredentials.googleapis.com as GenerateAccessToken. The latter are Data Access logs, which are off by default for most services, so enable them for IAM Credentials in the projects you care about. They count toward Cloud Logging ingestion, which is billed per GiB beyond a free allotment (pricing); a pipeline writes a handful of entries per deploy, so scope the setting to this one API rather than the whole project. WIF itself has no charge.
protoPayload.serviceName="iamcredentials.googleapis.com"
protoPayload.methodName="GenerateAccessToken"
protoPayload.authenticationInfo.principalSubject:"workloadIdentityPools/github"The principalSubject contains the GitHub subject, so you can tie a token to a repository and environment, and from the Cloud Run revision's creation time back to the workflow run.
Close the old door#
Once federation works, delete the JSON keys it replaced, remove the GitHub secrets that held them, and enforce the iam.managed.disableServiceAccountKeyCreation organization policy so nobody recreates one next quarter. I apply the same rule to laptops: local development uses personal identities with short-lived tokens minted by the CLI, never a shared dev key file. It costs an occasional re-login, and an expired local token has cost me a deploy afternoon, but revocation is then per person and every action in the console traces to a named identity. It is the managed successor to the legacy iam.disableServiceAccountKeyCreation, which organizations created since May 2024 already enforce by default.
A few limits remain. A condition that trusts your whole org plus a principalSet on repository_owner lets any repository in the org impersonate that account, including a test repository created this afternoon, so bind to repositories or subjects. The token lives for the whole job, so keep deploy jobs short and do not run untrusted code in the job that authenticates. A persistent self-hosted runner shared across repositories can leak credentials between jobs; use ephemeral runners. And federation needs an issuer that can produce a verifiable OIDC token: a pipeline already running on Google Cloud, in Cloud Build for example, has a native identity and does not need GitHub-to-Google federation at all.
Related articles
All articles →A Firestore rules deploy replaces everything at once, with no canary. The traps in the rules and the release path, and the pipeline that catches them.
11 min
An Eventarc trigger delivering to a private Cloud Run service passes four identity checks. A 401/403 reference table, and the setup that keeps each one correct.
9 min
Validate the user's JWT once at API Gateway, pass identity downstream as a header, and close the bypass, spoofing and revocation gaps that design opens.
14 min