Replace GCP Service Account Keys with Workload Identity Federation: A Step-by-Step Guide
Summary
Workload identity federation lets a workload outside Google Cloud, such as a GitHub Actions job, exchange its own short-lived token for Google Cloud access, so it no longer needs a service account key. To switch safely, inventory user-managed keys, block new keys with organization policy, add a pool and provider, migrate each workload, then retire the old keys.
Quick steps
- Run the read-only inventory script to list user-managed keys, when each one last authenticated, and whether key creation is blocked.
- Enforce the key creation and key upload constraints at the organization, with exceptions only for projects that still need keys.
- Create a workload identity pool and an OpenID Connect (OIDC) provider in a dedicated project, with an attribute condition on your GitHub organization ID.
- Grant one repository access: roles directly on resources, or Workload Identity User on a service account.
- Let the workflow request an OIDC token (
id-token: write) and authenticate withgoogle-github-actions/auth. - Disable each old key, watch the workload, then delete the key and the secret that stored it.
- Alert on new keys, pool and provider changes, and organization policy changes.
Applies to: Google Cloud IAM Workload Identity Federation and the Organization Policy Service, GitHub Actions on GitHub.com, and the google-github-actions/auth v3 action (as of November 2026). The scripts use bash and the Google Cloud CLI (gcloud).
What is workload identity federation and why does it matter?
Workload identity federation is a Google Cloud IAM feature that lets workloads outside Google Cloud reach Google Cloud resources with federated identities instead of service account keys. Google's Workload Identity Federation overview lists the sources it accepts: workloads on AWS or Azure, X.509 client certificates, on-premises Active Directory, pipelines such as GitHub and GitLab, and any identity provider (IdP) that supports OIDC or SAML 2.0. The workload identity federation glossary entry explains the concept; this guide is the migration.
Why are GCP service account keys risky?
A Google Cloud service account authenticates with an RSA key pair, and the private key of a user-managed key works like a password. Google's key management best practices name the threats: credential leakage, privilege escalation, information disclosure, non-repudiation and malicious credential configurations. Google also notes that a leaked key is more likely to work than a leaked password for an account with 2-step verification, because service accounts face no additional sign-in checks.
By default, keys that you create and download from IAM have no expiry time and stay valid until someone deletes them. A copy in a repository, a CI variable or a backup is a long-lived secret that keeps working. Attackers create keys for persistence too: MITRE ATT&CK cites gcloud iam service-accounts keys create under T1098.001, Additional Cloud Credentials.
How does the federated token exchange work?
Federation follows the OAuth 2.0 token exchange specification. The workload presents a credential from its own IdP to Google's Security Token Service, which verifies it and returns a short-lived federated token. These parts decide who gets in:
| Part | What it does |
|---|---|
| Workload identity pool | Manages external identities; Google recommends one pool per environment, such as development, staging and production |
| Workload identity pool provider | Describes the trust with one IdP: issuer URL, allowed audiences, mappings and condition |
| Attribute mapping | Common Expression Language (CEL) expressions that set google.subject (required, unique, at most 127 characters), google.groups and up to 50 custom attribute.NAME values from the IdP's claims |
| Attribute condition | A CEL expression; a credential is accepted only when it evaluates to true |
| Principal identifier | How allow policies name federated identities: by subject, group or attribute |
Direct resource access or service account impersonation?
Google recommends granting roles to the federated principal directly on resources, which it calls direct resource access. Most Google Cloud APIs support federated tokens, but some have limitations. For those, use service account impersonation: grant the federated identity Workload Identity User (roles/iam.workloadIdentityUser) on a service account, which holds the roles instead.
| Direct resource access | Service account impersonation | |
|---|---|---|
| Who holds the roles | The federated principal or principal set | A service account |
| Binding to create | Roles on each resource | roles/iam.workloadIdentityUser on the service account |
| API support | Most Google Cloud APIs; check Google's limitations list | All Google services accept the short-lived service account credentials |
| Audit trail | The federated principal | The service account as principalEmail, with the federated subject in serviceAccountDelegationInfo, as in Google's example entries |
Bindings name federated identities with these formats, always with the project number, not the project ID:
| Grant to | Principal identifier |
|---|---|
| One identity | principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/subject/SUBJECT_ATTRIBUTE_VALUE |
| A group | principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/group/GROUP_ID |
| Identities with an attribute value | principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/attribute.ATTRIBUTE_NAME/ATTRIBUTE_VALUE |
| Every identity in the pool | principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/* |
Google warns that granting access to every identity in a pool carries risk; limit access with attributes and conditions instead.
Before you start
Moving a workload off a key changes how it authenticates, so plan workload by workload and keep each key until its replacement works. Test the pool, the provider and the organization policies in a test project or folder first.
- Roles: Workload Identity Pool Admin (
roles/iam.workloadIdentityPoolAdmin) on the pool project, Organization Policy Administrator (roles/orgpolicy.policyAdmin) on the organization, and Service Account Key Admin (roles/iam.serviceAccountKeyAdmin) to disable and delete keys. Owner and Editor don't includeorgpolicy.policy.set, so they can't change the constraints. - A dedicated project: Google recommends managing all workload identity pools and providers in one project, so few people can change mappings and conditions. Enable the IAM, Resource Manager, Service Account Credentials and Security Token Service APIs there.
- Audit logs: enable Data Access audit logs, log type Admin Read, for the IAM API and the Security Token Service API in projects that hold pools or federated service accounts. Google says you need them to get audit entries for every step of the token exchange.
- Impact: the key constraints aren't retroactive. They don't break workloads that use existing keys, but they do stop any process that creates or rotates keys.
- Owners: list who owns each key-based workload. Google's migration guide expects workload owners to choose the replacement and do the refactoring.
Step 1: Inventory service account keys and their usage
Start with a list of every user-managed key, its service account, when it last authenticated, and whether new keys are already blocked. Key lists also show Google-managed keys that the Service Account Credentials API uses, so the script asks only for user-managed keys (--managed-by=user).
The script below is read-only. The key list API returns metadata such as the key ID, validity times and status; it never returns the private key. Last use comes from Activity Analyzer (gcloud policy-intelligence query-activity), which is in Preview as of November 2026 and needs the Policy Analyzer API. Run it in Cloud Shell with View Service Accounts, Activity Analysis Viewer and Organization Policy Viewer on each project.
#!/usr/bin/env bash
#
# gcp-sa-key-inventory.sh
#
# Purpose: Inventory user-managed service account keys in Google Cloud
# projects, show when each key last authenticated, and report the
# effective key organization policies. Writes CSV reports and prints
# a summary:
# sa-keys.csv one row per user-managed key
# key-constraints.csv effective key constraints per project
# Mode: Read-only. Uses list, describe and query commands only. It never
# creates, downloads or prints key material: the key list returns
# metadata (key ID, validity times, origin, status), not private keys.
# Auth: Run as a principal with these roles on each project:
# roles/iam.serviceAccountViewer (service accounts and keys)
# roles/policyanalyzer.activityAnalysisViewer (last key use)
# roles/orgpolicy.policyViewer (effective organization policies)
# The last-use query needs the Policy Analyzer API in the project.
# Without it, last_authenticated reads "unknown".
# Where: Cloud Shell or a Linux admin workstation with the Google Cloud CLI
# (gcloud). The cutoff date uses GNU date.
# Usage: gcp-sa-key-inventory.sh <output-dir> [--unused-days <n>] [<project-id> ...]
# Without project IDs, it reads every project gcloud projects list returns.
# Example: gcp-sa-key-inventory.sh ./sa-key-inventory --unused-days 90 example-project
set -euo pipefail
USAGE='usage: gcp-sa-key-inventory.sh <output-dir> [--unused-days <n>] [<project-id> ...]'
OUT_DIR="${1:?$USAGE}"
shift
UNUSED_DAYS=90
PROJECTS=()
while [ "$#" -gt 0 ]; do
case "$1" in
--unused-days) UNUSED_DAYS="${2:?--unused-days needs a number of days}"; shift 2 ;;
-*) echo "Unknown option: $1" >&2; exit 2 ;;
*) PROJECTS+=("$1"); shift ;;
esac
done
if ! [[ "$UNUSED_DAYS" =~ ^[0-9]+$ ]]; then
echo "--unused-days must be a whole number of days." >&2
exit 2
fi
command -v gcloud >/dev/null 2>&1 || { echo "The Google Cloud CLI (gcloud) is not installed." >&2; exit 1; }
if [ "${#PROJECTS[@]}" -eq 0 ]; then
mapfile -t PROJECTS < <(gcloud projects list --format='value(projectId)')
fi
for project in "${PROJECTS[@]}"; do
if ! [[ "$project" =~ ^[a-z0-9.:-]+$ ]]; then
echo "Not a project ID: $project" >&2
exit 2
fi
done
mkdir -p "$OUT_DIR"
CUTOFF="$(date -u -d "-${UNUSED_DAYS} days" +%Y-%m-%dT%H:%M:%SZ)"
KEYS_CSV="$OUT_DIR/sa-keys.csv"
POLICY_CSV="$OUT_DIR/key-constraints.csv"
echo 'findings,project,service_account,key_id,key_origin,valid_after,valid_before,disabled,disable_reason,last_authenticated' > "$KEYS_CSV"
echo 'project,constraint,enforced' > "$POLICY_CSV"
CONSTRAINTS=(
iam.disableServiceAccountKeyCreation
iam.managed.disableServiceAccountKeyCreation
iam.disableServiceAccountKeyUpload
iam.managed.disableServiceAccountKeyUpload
)
for project in "${PROJECTS[@]}"; do
# 1. Effective key constraints (legacy and managed names)
for constraint in "${CONSTRAINTS[@]}"; do
state="$(gcloud org-policies describe "$constraint" --project="$project" --effective \
--format='value(spec.rules[0].enforce)' 2>/dev/null || true)"
echo "${project},${constraint},${state:-unset}" >> "$POLICY_CSV"
done
# 2. Last authentication per key ID (Activity Analyzer, Preview)
unset LAST_AUTH
declare -A LAST_AUTH=()
ACTIVITY_OK=false
if activity="$(gcloud policy-intelligence query-activity \
--activity-type=serviceAccountKeyLastAuthentication --project="$project" \
--limit=unlimited \
--format='csv[no-heading](fullResourceName.basename(),activity.lastAuthenticatedTime)' 2>/dev/null)"; then
ACTIVITY_OK=true
while IFS=, read -r key_id last; do
if [ -n "$key_id" ]; then LAST_AUTH["$key_id"]="$last"; fi
done <<< "$activity"
fi
# 3. User-managed keys of every service account in the project
mapfile -t accounts < <(gcloud iam service-accounts list --project="$project" --format='value(email)')
for sa in "${accounts[@]}"; do
while IFS=, read -r key_id origin after before disabled reason; do
if [ -z "$key_id" ]; then continue; fi
findings=()
if [[ "$before" == 9999-* ]]; then findings+=("no_expiry"); fi
if [ "$origin" = "USER_PROVIDED" ]; then findings+=("uploaded"); fi
if [[ "$reason" == *EXPOSED* || "$reason" == *COMPROMISE* ]]; then findings+=("exposed"); fi
if [ "${disabled,,}" = "true" ]; then findings+=("disabled"); fi
if [ "$ACTIVITY_OK" = true ]; then
last="${LAST_AUTH[$key_id]:-}"
if [ -z "$last" ] || [[ "$last" < "$CUTOFF" ]]; then findings+=("unused_${UNUSED_DAYS}d"); fi
else
last="unknown"
fi
printf '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n' "$(IFS=';'; echo "${findings[*]:-}")" \
"$project" "$sa" "$key_id" "$origin" "$after" "$before" "$disabled" "$reason" "$last" >> "$KEYS_CSV"
done < <(gcloud iam service-accounts keys list --iam-account="$sa" --project="$project" \
--managed-by=user \
--format='csv[no-heading](name.basename(),keyOrigin,validAfterTime,validBeforeTime,disabled.yesno(yes="True",no="False"),disableReason)')
done
done
# 4. Summary (findings is the first column)
rows() { echo $(( $(wc -l < "$1") - 1 )); }
flag() { grep -c "^[^,]*$2" "$1" || true; }
open_projects="$(awk -F, 'NR > 1 && $2 ~ /disableServiceAccountKeyCreation$/ {
seen[$1] = 1; if (tolower($3) == "true") on[$1] = 1 }
END { n = 0; for (p in seen) if (!(p in on)) n++; print n }' "$POLICY_CSV")"
printf 'Projects scanned : %s\n' "${#PROJECTS[@]}"
printf 'Key creation not blocked in : %s project(s)\n' "$open_projects"
printf 'User-managed keys : %s\n' "$(rows "$KEYS_CSV")"
printf ' no_expiry : %s\n' "$(flag "$KEYS_CSV" no_expiry)"
printf ' unused_%sd : %s\n' "$UNUSED_DAYS" "$(flag "$KEYS_CSV" "unused_${UNUSED_DAYS}d")"
printf ' uploaded : %s\n' "$(flag "$KEYS_CSV" uploaded)"
printf ' exposed : %s\n' "$(flag "$KEYS_CSV" exposed)"
printf ' disabled : %s\n' "$(flag "$KEYS_CSV" disabled)"
printf 'Reports : %s\n' "$OUT_DIR"
Run it for one project, or without project IDs for every project your account can list:
bash gcp-sa-key-inventory.sh ./sa-key-inventory --unused-days 90 example-project
Example output (the values are illustrative):
Projects scanned : 1
Key creation not blocked in : 1 project(s)
User-managed keys : 6
no_expiry : 5
unused_90d : 3
uploaded : 1
exposed : 0
disabled : 1
Reports : ./sa-key-inventory
How to read the findings column:
- no_expiry: the key's
validBeforeTimeis in the year 9999, like9999-12-31T23:59:59Zin Google's key list example, which marks a key without an expiry time. Plan to replace it with federation. - unused_90d: Activity Analyzer recorded no authentication in the last 90 days, or none at all in its observation period. Google's migration guide treats such keys as possible quick wins.
- uploaded: the key origin is
USER_PROVIDED, so someone generated the private key outside Google Cloud and uploaded the public key. - exposed: the disable reason says Google detected the key as exposed or compromised. Treat the key as leaked and review what the service account did.
- unset in
key-constraints.csv: the effective policy returned noenforcevalue for that constraint name, so the script counts the constraint as not enforced. A project counts as blocked when either the legacy or the managed key creation constraint readsTrue.
Activity Analyzer has blind spots, so cross-check before you delete anything. It doesn't track authentication to Google APIs outside Google Cloud, such as domain-wide delegation to Google Workspace, and its timestamps are always T07:00:00Z. Google suggests comparing the results with the Cloud Monitoring metric Service account key authentication events, which keeps 6 weeks of data. For an organization-wide view, the reference architecture in Google's migration guide queries Cloud Asset Inventory, which lists iam.googleapis.com/ServiceAccountKey as a resource type:
gcloud asset search-all-resources --scope=organizations/000000000000 \
--asset-types=iam.googleapis.com/ServiceAccountKey
Step 2: Disable service account key creation with organization policy
Organization policy constraints stop new keys at the source, so the inventory doesn't grow back while you migrate. Google recommends enforcing Disable service account key creation and Disable service account key upload at the root of the resource hierarchy, then overriding them only for projects that can't use a safer alternative.
Is key creation already blocked in your organization?
As of November 2026, Google enforces a security baseline on every organization created on or after May 3, 2024; some created between February and April 2024 might have it too. The baseline covers key creation and key upload. Google's pages disagree on which constraint names carry it: the security baseline page lists iam.managed.disableServiceAccountKeyCreation and iam.disableServiceAccountKeyUpload, while the constraint reference marks the legacy iam.disableServiceAccountKeyCreation as part of the baseline. The inventory script checks all four names for that reason.
Older organizations, and folders or projects that override the policy, need the constraints set explicitly. These are the settings, from Google's service account constraint page:
| Setting | Where | Recommended value | Effect |
|---|---|---|---|
Disable service account key creation: iam.managed.disableServiceAccountKeyCreation (managed) or iam.disableServiceAccountKeyCreation (legacy) |
Organization policies, at the organization | Enforced | Blocks new user-managed keys and Cloud Storage HMAC keys; existing keys keep working |
Disable service account key upload: iam.managed.disableServiceAccountKeyUpload (managed) or iam.disableServiceAccountKeyUpload (legacy) |
Organization policies, at the organization | Enforced | Blocks uploading public keys to service accounts |
iam.serviceAccountKeyExposureResponse |
Organization policies, at the organization | DISABLE_KEY |
Google disables keys it detects as exposed; since June 16, 2024 this is also the behavior when the constraint isn't set |
iam.serviceAccountKeyExpiryHours |
Exception projects only, for non-production use | The shortest allowed value that fits, from 1h to 2160h |
New keys expire; existing keys don't change |
iam.workloadIdentityPoolProviders |
Deny all at the organization, allow trusted issuers in the pool project | Issuer URIs you trust, such as GitHub's | Stops new providers for issuers you didn't allow |
Google advises against expiry times for production keys, because an expired key can cause an outage. Google recommends managed equivalents over legacy constraints such as key upload, for more flexibility and better insight from Policy Intelligence tools. Managed constraints can also run in dry-run mode: on the constraint's Dry run tab, Manage dry run policy and then Set dry run policy log violations in the audit logs without denying them.
Apply the constraints
The script below writes the organization policy files and, only with --apply, sets them with gcloud org-policies set-policy. Run it as an Organization Policy Administrator from Cloud Shell. With --exception-project, it also writes project policies that allow key creation again in that one project, under both constraint names; a project policy replaces an inherited managed constraint rather than merging with it.
#!/usr/bin/env bash
#
# enforce-key-constraints.sh
#
# Purpose: Block new user-managed service account keys for a Google Cloud
# organization with organization policies set at the organization:
# iam.managed.disableServiceAccountKeyCreation enforce: true
# iam.managed.disableServiceAccountKeyUpload enforce: true
# iam.serviceAccountKeyExposureResponse DISABLE_KEY
# With --exception-project, that one project gets policies that allow
# key creation again (legacy and managed constraint).
# Mode: Changes configuration, but only with --apply. Without --apply it is
# a dry run: it writes the policy files and prints the commands.
# Effect: The constraints stop new keys. Existing keys keep working until
# you disable or delete them.
# Auth: roles/orgpolicy.policyAdmin on the organization.
# Where: Cloud Shell or an admin workstation with the Google Cloud CLI.
# Usage: enforce-key-constraints.sh <organization-id> <policy-dir> [--exception-project <project-id>] [--apply]
# Example: enforce-key-constraints.sh 000000000000 ./key-policies
# enforce-key-constraints.sh 000000000000 ./key-policies --apply
set -euo pipefail
USAGE='usage: enforce-key-constraints.sh <organization-id> <policy-dir> [--exception-project <project-id>] [--apply]'
ORG_ID="${1:?$USAGE}"
POLICY_DIR="${2:?$USAGE}"
shift 2
EXCEPTION_PROJECT=""
APPLY=false
while [ "$#" -gt 0 ]; do
case "$1" in
--exception-project) EXCEPTION_PROJECT="${2:?--exception-project needs a project ID}"; shift 2 ;;
--apply) APPLY=true; shift ;;
*) echo "Unknown option: $1" >&2; exit 2 ;;
esac
done
if ! [[ "$ORG_ID" =~ ^[0-9]+$ ]]; then
echo "The organization ID is a number, for example 000000000000." >&2
exit 2
fi
if [ -n "$EXCEPTION_PROJECT" ] && ! [[ "$EXCEPTION_PROJECT" =~ ^[a-z0-9.:-]+$ ]]; then
echo "Not a project ID: $EXCEPTION_PROJECT" >&2
exit 2
fi
command -v gcloud >/dev/null 2>&1 || { echo "The Google Cloud CLI (gcloud) is not installed." >&2; exit 1; }
mkdir -p "$POLICY_DIR"
# write_policy <file> <policy name> <rules block>
write_policy() {
printf 'name: %s\nspec:\n rules:\n%s\n' "$2" "$3" > "$1"
FILES+=("$1")
}
FILES=()
ORG="organizations/${ORG_ID}/policies"
write_policy "$POLICY_DIR/org-disable-key-creation.yaml" \
"${ORG}/iam.managed.disableServiceAccountKeyCreation" ' - enforce: true'
write_policy "$POLICY_DIR/org-disable-key-upload.yaml" \
"${ORG}/iam.managed.disableServiceAccountKeyUpload" ' - enforce: true'
write_policy "$POLICY_DIR/org-key-exposure-response.yaml" \
"${ORG}/iam.serviceAccountKeyExposureResponse" $' - values:\n allowedValues:\n - DISABLE_KEY'
if [ -n "$EXCEPTION_PROJECT" ]; then
PRJ="projects/${EXCEPTION_PROJECT}/policies"
write_policy "$POLICY_DIR/exception-legacy-key-creation.yaml" \
"${PRJ}/iam.disableServiceAccountKeyCreation" ' - enforce: false'
write_policy "$POLICY_DIR/exception-managed-key-creation.yaml" \
"${PRJ}/iam.managed.disableServiceAccountKeyCreation" ' - enforce: false'
fi
for file in "${FILES[@]}"; do
echo "--- ${file}"
cat "$file"
if [ "$APPLY" = true ]; then
gcloud org-policies set-policy "$file"
else
echo "Would run: gcloud org-policies set-policy ${file}"
fi
done
if [ "$APPLY" != true ]; then
echo "Dry run: no policy was changed. Review the files, then run again with --apply." >&2
fi
Run the dry run first and read the files it writes:
bash enforce-key-constraints.sh 000000000000 ./key-policies
--- ./key-policies/org-disable-key-creation.yaml
name: organizations/000000000000/policies/iam.managed.disableServiceAccountKeyCreation
spec:
rules:
- enforce: true
Would run: gcloud org-policies set-policy ./key-policies/org-disable-key-creation.yaml
--- ./key-policies/org-disable-key-upload.yaml
name: organizations/000000000000/policies/iam.managed.disableServiceAccountKeyUpload
spec:
rules:
- enforce: true
Would run: gcloud org-policies set-policy ./key-policies/org-disable-key-upload.yaml
--- ./key-policies/org-key-exposure-response.yaml
name: organizations/000000000000/policies/iam.serviceAccountKeyExposureResponse
spec:
rules:
- values:
allowedValues:
- DISABLE_KEY
Would run: gcloud org-policies set-policy ./key-policies/org-key-exposure-response.yaml
Dry run: no policy was changed. Review the files, then run again with --apply.
Step 3: Create a workload identity pool and GitHub provider
Create the pool and provider in the dedicated project, one provider per pool. GitHub uses one issuer URL for every organization, so the issuer alone doesn't show which organization a token came from. Google's deployment pipeline guide says you must use an attribute condition that restricts access to tokens issued by your GitHub organization. Google's API reference says multi-tenant providers such as GitHub require one.
Use GitHub's numeric IDs rather than names. Google warns that repository and repository_owner invite cybersquatting and typosquatting: if you delete a repository or organization, someone else might claim the name. The repository_id and repository_owner_id values are unique and never reused. Look them up once with GitHub CLI:
gh api repos/example-org/example-repo --jq '.id, .owner.id'
12345678
87654321
The provider maps these claims. Google's minimum is google.subject=assertion.sub, and every claim that a condition or binding uses must be mapped:
| Mapping | Why |
|---|---|
google.subject=assertion.sub |
The subject that appears in audit logs |
attribute.repository_id=assertion.repository_id |
Numeric repository ID, used in the principal set |
attribute.repository_owner_id=assertion.repository_owner_id |
Numeric organization ID, used in the condition |
attribute.ref=assertion.ref |
Branch or tag, for an optional --ref condition |
The subject format is changing. Per the GitHub OIDC reference, repositories created after July 15, 2026, and repositories renamed or transferred after that date, get an immutable sub such as repo:octo-org@123456/octo-repo@456789:ref:refs/heads/main. Older repositories keep the name-only format unless you opt in. Binding on attribute.repository_id works with both formats.
The script below creates the pool, the provider and the binding. It needs Workload Identity Pool Admin on the project, plus Service Account Admin on the service account when you pass --service-account. Without --apply, it only reads the project number and prints the commands.
#!/usr/bin/env bash
#
# create-github-wif.sh
#
# Purpose: Create a workload identity pool and a GitHub Actions OIDC provider
# in a dedicated Google Cloud project, and give one GitHub repository
# access through it. The provider accepts tokens only from one GitHub
# organization (numeric owner ID). Access goes to one repository
# (numeric repository ID):
# with --service-account: roles/iam.workloadIdentityUser on that
# service account (service account impersonation)
# without it: the script prints the principal set to grant roles
# on resources (direct resource access)
# Mode: Changes configuration, but only with --apply. Without --apply it is
# a dry run: it reads the project number and prints the commands.
# Auth: roles/iam.workloadIdentityPoolAdmin on the project. With
# --service-account, also a role that can change the service
# account's allow policy, such as roles/iam.serviceAccountAdmin.
# Where: Cloud Shell or an admin workstation with the Google Cloud CLI.
# Usage: create-github-wif.sh <project-id> <github-owner-id> <github-repository-id>
# [--pool <id>] [--provider <id>] [--ref <git-ref>]
# [--service-account <email>] [--apply]
# Example: create-github-wif.sh example-project 87654321 12345678 \
# --ref refs/heads/main \
# --service-account deployer@example-project.iam.gserviceaccount.com
set -euo pipefail
USAGE='usage: create-github-wif.sh <project-id> <github-owner-id> <github-repository-id> [--pool <id>] [--provider <id>] [--ref <git-ref>] [--service-account <email>] [--apply]'
PROJECT_ID="${1:?$USAGE}"
OWNER_ID="${2:?$USAGE}"
REPO_ID="${3:?$USAGE}"
shift 3
POOL_ID="github-pool"
PROVIDER_ID="github-provider"
GIT_REF=""
SERVICE_ACCOUNT=""
APPLY=false
while [ "$#" -gt 0 ]; do
case "$1" in
--pool) POOL_ID="${2:?--pool needs an ID}"; shift 2 ;;
--provider) PROVIDER_ID="${2:?--provider needs an ID}"; shift 2 ;;
--ref) GIT_REF="${2:?--ref needs a Git ref such as refs/heads/main}"; shift 2 ;;
--service-account) SERVICE_ACCOUNT="${2:?--service-account needs an email address}"; shift 2 ;;
--apply) APPLY=true; shift ;;
*) echo "Unknown option: $1" >&2; exit 2 ;;
esac
done
if ! [[ "$OWNER_ID" =~ ^[0-9]+$ && "$REPO_ID" =~ ^[0-9]+$ ]]; then
echo "Use the numeric GitHub owner ID and repository ID, not their names." >&2
exit 2
fi
for id in "$POOL_ID" "$PROVIDER_ID"; do
if ! [[ "$id" =~ ^[a-z0-9-]{4,32}$ ]] || [[ "$id" == gcp-* ]]; then
echo "Pool and provider IDs need 4 to 32 characters [a-z0-9-] and can't start with gcp-: $id" >&2
exit 2
fi
done
if [ -n "$GIT_REF" ] && ! [[ "$GIT_REF" =~ ^refs/(heads|tags)/[A-Za-z0-9._/-]+$ ]]; then
echo "--ref takes a full Git ref, for example refs/heads/main." >&2
exit 2
fi
command -v gcloud >/dev/null 2>&1 || { echo "The Google Cloud CLI (gcloud) is not installed." >&2; exit 1; }
# Read-only: the principal identifiers need the project number, not the ID.
PROJECT_NUMBER="$(gcloud projects describe "$PROJECT_ID" --format='value(projectNumber)')"
MAPPING="google.subject=assertion.sub,attribute.repository_id=assertion.repository_id,attribute.repository_owner_id=assertion.repository_owner_id,attribute.ref=assertion.ref"
CONDITION="assertion.repository_owner_id=='${OWNER_ID}'"
if [ -n "$GIT_REF" ]; then
CONDITION="${CONDITION} && assertion.ref=='${GIT_REF}'"
fi
POOL_NAME="projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL_ID}"
PRINCIPAL_SET="principalSet://iam.googleapis.com/${POOL_NAME}/attribute.repository_id/${REPO_ID}"
run() {
if [ "$APPLY" = true ]; then
"$@"
else
printf 'Would run:'
printf ' %q' "$@"
printf '\n'
fi
}
run gcloud iam workload-identity-pools create "$POOL_ID" \
--project="$PROJECT_ID" --location="global" \
--display-name="GitHub Actions" \
--description="GitHub Actions workflows of one GitHub organization"
run gcloud iam workload-identity-pools providers create-oidc "$PROVIDER_ID" \
--project="$PROJECT_ID" --location="global" \
--workload-identity-pool="$POOL_ID" \
--display-name="GitHub Actions OIDC" \
--issuer-uri="https://token.actions.githubusercontent.com/" \
--attribute-mapping="$MAPPING" \
--attribute-condition="$CONDITION"
if [ -n "$SERVICE_ACCOUNT" ]; then
run gcloud iam service-accounts add-iam-policy-binding "$SERVICE_ACCOUNT" \
--project="$PROJECT_ID" \
--role="roles/iam.workloadIdentityUser" \
--member="$PRINCIPAL_SET"
else
echo "Direct resource access: grant roles on each resource to ${PRINCIPAL_SET}"
fi
echo "workload_identity_provider: ${POOL_NAME}/providers/${PROVIDER_ID}"
if [ "$APPLY" != true ]; then
echo "Dry run: nothing was created. Run again with --apply to make these changes." >&2
fi
Run the dry run with your IDs:
bash create-github-wif.sh example-project 87654321 12345678 --ref refs/heads/main \
--service-account deployer@example-project.iam.gserviceaccount.com
Would run: gcloud iam workload-identity-pools create github-pool --project=example-project --location=global --display-name=GitHub\ Actions --description=GitHub\ Actions\ workflows\ of\ one\ GitHub\ organization
Would run: gcloud iam workload-identity-pools providers create-oidc github-provider --project=example-project --location=global --workload-identity-pool=github-pool --display-name=GitHub\ Actions\ OIDC --issuer-uri=https://token.actions.githubusercontent.com/ --attribute-mapping=google.subject=assertion.sub\,attribute.repository_id=assertion.repository_id\,attribute.repository_owner_id=assertion.repository_owner_id\,attribute.ref=assertion.ref --attribute-condition=assertion.repository_owner_id==\'87654321\'\ \&\&\ assertion.ref==\'refs/heads/main\'
Would run: gcloud iam service-accounts add-iam-policy-binding deployer@example-project.iam.gserviceaccount.com --project=example-project --role=roles/iam.workloadIdentityUser --member=principalSet://iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/github-pool/attribute.repository_id/12345678
workload_identity_provider: projects/123456789012/locations/global/workloadIdentityPools/github-pool/providers/github-provider
Dry run: nothing was created. Run again with --apply to make these changes.
The pool and provider IDs can't change later, and the gcp- prefix is reserved. The console does the same on the New workload provider and pool page: select OpenID Connect (OIDC), enter the issuer URL, keep Default audience, then add the mappings and the condition.
Grant access to one repository
Grant roles to the principal set for one repository, never to the whole pool. Google's federation best practices say to avoid granting roles/iam.workloadIdentityUser to all members of a pool and to use a dedicated service account per application. For direct resource access, grant the role on the resource itself; this example lets the repository upload release files to one bucket:
gcloud storage buckets add-iam-policy-binding gs://example-project-releases \
--role=roles/storage.objectCreator \
--member="principalSet://iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/github-pool/attribute.repository_id/12345678"
Keep roles narrow either way, as least privilege in Google Cloud IAM describes. A federated workflow can use every role that its service account or principal set holds.
Step 4: Authenticate GitHub Actions without a key
The workflow needs two changes: permission to request an OIDC token, and the google-github-actions/auth action instead of a key. GitHub's Google Cloud OIDC guide explains that id-token: write only lets the job request and use an OIDC token; it doesn't grant write access to other resources.
The action's README lists these inputs and rules for version 3:
workload_identity_provider(required): the full provider name with the project number, as the script prints it.service_account(optional): the service account to impersonate. Leave it out for direct resource access.project_id(optional): the action can't derive the project ID from the provider name, which holds only the project number. Set it when later steps, such asgcloudcommands, need a project ID.- Run
actions/checkoutbeforeauth; otherwise later steps can't authenticate. - The credentials file goes into
$GITHUB_WORKSPACEand is removed when the job ends. Addgha-creds-*.jsonto.gitignoreand.dockerignore. gsutildoesn't use these credentials; usegcloud storage.
The README also states that the action isn't an officially supported Google product, even though Google's pipeline guide uses it. Save the workflow as .github/workflows/deploy-gcp.yml:
# .github/workflows/deploy-gcp.yml
# Authenticates to Google Cloud with Workload Identity Federation: no service
# account key and no Google Cloud secret is stored in GitHub. The values are
# this guide's examples; take yours from the output of create-github-wif.sh.
name: Deploy to Google Cloud
on:
push:
branches:
- main
permissions:
contents: read
id-token: write
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- name: Authenticate to Google Cloud
id: auth
uses: google-github-actions/auth@v3
with:
project_id: example-project
workload_identity_provider: projects/123456789012/locations/global/workloadIdentityPools/github-pool/providers/github-provider
# Service account impersonation. Remove this line for direct resource access.
service_account: deployer@example-project.iam.gserviceaccount.com
- name: Set up the Google Cloud CLI
uses: google-github-actions/setup-gcloud@v3
- name: Deploy
run: gcloud storage cp ./dist/app.tar.gz gs://example-project-releases/
Pools, providers and IAM permissions can take up to 5 minutes to propagate, so wait before the first run. If the job uses a deployment environment, GitHub recommends protection rules on that environment. Once the run succeeds, delete the repository secret that held the key JSON, for example with gh secret delete GCP_SA_KEY --repo example-org/example-repo. The GitHub personal access token guide covers the other long-lived credentials in the same repositories.
Other platforms: AWS, Azure and other OIDC providers
The same pattern works outside GitHub; only the provider and the credential source change. Google's pipeline guide and its pages for other clouds and providers give the exact settings:
| Platform | Provider | Settings to check |
|---|---|---|
| AWS | gcloud iam workload-identity-pools providers create-aws with --account-id |
Without a custom mapping, Google maps google.subject to assertion.arn and sets attribute.aws_role; restrict AWS accounts with iam.workloadIdentityPoolAwsAccounts |
| Azure | create-oidc with issuer https://sts.windows.net/TENANT_ID |
Allowed audience is the Application ID URI of the Entra ID application; for a managed identity, sub is its object ID |
| GitLab SaaS | create-oidc with issuer https://gitlab.com |
Condition on assertion.namespace_id, which Google also requires |
| HCP Terraform | create-oidc with issuer https://app.terraform.io |
Condition on assertion.terraform_organization_id |
| Other OIDC or SAML 2.0 IdPs | create-oidc or a SAML provider |
You must supply the attribute mappings |
Workloads that don't use the GitHub action read a credential configuration file from gcloud iam workload-identity-pools create-cred-config, with --aws, --azure or a token file, through GOOGLE_APPLICATION_CREDENTIALS. Ambient tokens still deserve care: Forestall's research on extracting managed identity tokens from Azure SQL Database shows how code with enough database rights can mint tokens for the server's identity. On the AWS side, moving from IAM users to IAM Identity Center retires access keys in the same way.
Step 5: Disable the old keys, then delete them
Retire each key in two moves: disable it, confirm nothing broke, then delete it. Google recommends this order: a disabled key can be enabled again at any time, but a deleted key can't be undeleted. Neither action revokes short-lived credentials already issued with the key; to revoke those you must disable or delete the service account, which cuts off every workload that uses it.
Disable keys with the CLI or the API; the console can show disabled keys but can't disable one. The script below works on one key at a time, needs Service Account Key Admin, and refuses to delete a key that isn't disabled yet. Without --apply it only shows the key's metadata.
#!/usr/bin/env bash
#
# retire-sa-key.sh
#
# Purpose: Disable, re-enable or delete one user-managed service account key
# after its workload has moved to Workload Identity Federation. Take
# the service account and key ID from sa-keys.csv
# (gcp-sa-key-inventory.sh).
# Mode: Changes configuration, but only with --apply. Without --apply it is
# a dry run: it shows the key's metadata and prints the command.
# Safety: delete refuses a key that isn't disabled yet. A deleted key can't
# be undeleted. Disabling or deleting a key doesn't revoke
# short-lived credentials that were already issued with it.
# Auth: roles/iam.serviceAccountKeyAdmin on the project or the service account.
# Where: Cloud Shell or an admin workstation with the Google Cloud CLI.
# Usage: retire-sa-key.sh <disable|enable|delete> <service-account-email> <key-id> [--apply]
# Example: retire-sa-key.sh disable ci-deployer@example-project.iam.gserviceaccount.com 0a1b2c3d4e5f60718293a4b5c6d7e8f901234567
set -euo pipefail
USAGE='usage: retire-sa-key.sh <disable|enable|delete> <service-account-email> <key-id> [--apply]'
ACTION="${1:?$USAGE}"
SERVICE_ACCOUNT="${2:?$USAGE}"
KEY_ID="${3:?$USAGE}"
APPLY=false
if [ "${4:-}" = "--apply" ]; then
APPLY=true
elif [ -n "${4:-}" ]; then
echo "Unknown option: $4" >&2
exit 2
fi
case "$ACTION" in
disable|enable|delete) ;;
*) echo "$USAGE" >&2; exit 2 ;;
esac
if ! [[ "$SERVICE_ACCOUNT" =~ ^[^@[:space:]]+@[^@[:space:]]+$ ]]; then
echo "Not a service account email address: $SERVICE_ACCOUNT" >&2
exit 2
fi
if ! [[ "$KEY_ID" =~ ^[0-9a-f]+$ ]]; then
echo "The key ID is the hexadecimal ID shown in the key list." >&2
exit 2
fi
command -v gcloud >/dev/null 2>&1 || { echo "The Google Cloud CLI (gcloud) is not installed." >&2; exit 1; }
# 1. Show the key (read-only: metadata only, never key material)
LINE="$(gcloud iam service-accounts keys list --iam-account="$SERVICE_ACCOUNT" --managed-by=user \
--format='csv[no-heading](name.basename(),validAfterTime,validBeforeTime,disabled.yesno(yes="True",no="False"))' \
| grep "^${KEY_ID}," || true)"
if [ -z "$LINE" ]; then
echo "No user-managed key ${KEY_ID} on ${SERVICE_ACCOUNT}." >&2
exit 1
fi
echo 'key_id,valid_after,valid_before,disabled'
echo "$LINE"
DISABLED="$(echo "$LINE" | cut -d, -f4)"
if [ "$ACTION" = "delete" ] && [ "${DISABLED,,}" != "true" ]; then
echo "Disable the key first, and delete it only when you're sure nothing uses it." >&2
exit 1
fi
# 2. Change (only with --apply)
CMD=(gcloud iam service-accounts keys "$ACTION" "$KEY_ID" --iam-account="$SERVICE_ACCOUNT")
if [ "$APPLY" != true ]; then
echo "Dry run: nothing changed. Run again with --apply to run: ${CMD[*]}" >&2
exit 0
fi
"${CMD[@]}"
echo "Done: ${ACTION} ${KEY_ID}. Run gcp-sa-key-inventory.sh again to confirm." >&2
bash retire-sa-key.sh disable ci-deployer@example-project.iam.gserviceaccount.com 0a1b2c3d4e5f60718293a4b5c6d7e8f901234567
key_id,valid_after,valid_before,disabled
0a1b2c3d4e5f60718293a4b5c6d7e8f901234567,2025-03-14T09:20:11Z,9999-12-31T23:59:59Z,False
Dry run: nothing changed. Run again with --apply to run: gcloud iam service-accounts keys disable 0a1b2c3d4e5f60718293a4b5c6d7e8f901234567 --iam-account=ci-deployer@example-project.iam.gserviceaccount.com
How long to wait between disable and delete is your call; Google only says to wait until you're sure the key isn't needed. Activity Analyzer and the key usage metric leave out disabled keys, so watch the workload's own job results and error logs during that time. Then run the script with delete and --apply.
Verify
Check each layer after the change: the policies, the federation trust, a real workflow run and the remaining keys.
| Check | Expected result |
|---|---|
Rerun gcp-sa-key-inventory.sh |
Key creation not blocked in: 0 project(s) apart from planned exceptions; migrated keys are gone |
gcloud org-policies describe iam.managed.disableServiceAccountKeyCreation --project=example-project --effective |
enforce: true under spec.rules |
gcloud iam workload-identity-pools providers describe github-provider --workload-identity-pool=github-pool --location=global --project=example-project --format='value(state,attributeCondition)' |
ACTIVE and your condition with the numeric owner ID |
gcloud iam service-accounts get-iam-policy deployer@example-project.iam.gserviceaccount.com |
roles/iam.workloadIdentityUser for the repository principal set only, with no pool-wide /* member |
| The workflow run | The auth step succeeds and the deploy step can reach its resources |
gcp-key-wif-audit-events.sh with --with-token-use |
An ExchangeToken entry with the GitHub subject, then a GenerateAccessToken record for the service account |
Roll back
Most of the migration can be reversed, but a deleted key can't. Keep the inventory reports as the record of which keys existed before the change.
| Change | How to roll back | Notes |
|---|---|---|
| Key disabled | retire-sa-key.sh enable <service-account> <key-id> --apply |
A disabled key can be enabled again at any time |
| Key deleted | Can't be undone | A replacement key needs a project where key creation is allowed |
| Organization constraint | gcloud org-policies delete iam.managed.disableServiceAccountKeyCreation --organization=000000000000 |
Repeat for each policy you set; if the legacy constraint is also enforced, for example by the security baseline, keys stay blocked until you change that policy too |
| Exception project | gcloud org-policies delete iam.managed.disableServiceAccountKeyCreation --project=example-project |
Repeat for the legacy name; the project inherits the organization policy again |
| Provider | gcloud iam workload-identity-pools providers update-oidc github-provider --workload-identity-pool=github-pool --location=global --disabled |
A disabled provider exchanges no new tokens, but tokens already issued keep working; --no-disabled turns it back on |
| Pool or provider deleted | gcloud iam workload-identity-pools undelete or providers undelete within 30 days |
Deleting a pool also deletes its providers, and its ID can't be reused until it is permanently deleted |
| Workload Identity User binding | gcloud iam service-accounts remove-iam-policy-binding with the same --member and --role |
Removes the repository's access to the service account |
Monitor and detect
Watch Cloud Audit Logs for new keys, changes to the federation trust and weakened key constraints. Google's IAM audit logging reference lists the method names; Admin Activity logs are always written, while token exchanges need the Data Access logs from Before you start. The site's detection rule pages carry Sigma rules with Splunk, Microsoft Sentinel and QRadar queries.
| Audit log method | What it means | Related detection rules |
|---|---|---|
google.iam.admin.v1.CreateServiceAccountKey |
A user-managed key was created | User-managed key created rules |
google.iam.admin.v1.UploadServiceAccountKey |
A public key was uploaded | Same rules |
google.iam.admin.v1.DisableServiceAccountKey and DeleteServiceAccountKey |
A key was disabled or deleted; when Google disables an exposed key, the caller is gcp-compromised-key-response@system.gserviceaccount.com |
Key disabled or deleted rules |
google.iam.admin.v1.EnableServiceAccountKey |
A disabled key was enabled again | Disabled key restored rules |
google.iam.v1.WorkloadIdentityPools.CreateWorkloadIdentityPool, CreateWorkloadIdentityPoolProvider, UpdateWorkloadIdentityPoolProvider |
A pool or provider was created, or a mapping or condition changed | Pool or provider created or changed rules |
google.iam.v1.WorkloadIdentityPools.SetIamPolicy |
The allow policy of a pool was replaced | Same rules |
google.iam.admin.v1.SetIAMPolicy |
A service account's allow policy changed, for example a new Workload Identity User | Impersonation rights granted rules |
google.cloud.orgpolicy.v2.OrgPolicy.UpdatePolicy and DeletePolicy |
An organization policy, such as a key constraint, changed or was removed | Organization policy changed rules |
google.identity.sts.v1.SecurityTokenService.ExchangeToken |
An IdP token was exchanged; principalSubject holds the GitHub sub |
Data Access log; Google's example entries note that client-side failures aren't logged |
GenerateAccessToken |
Short-lived credentials were issued for a service account | Service account impersonation rules cover user accounts; federated callers need your own baseline |
A role granted to a federated principal set shows up in the allow policy of the resource. The pool rules above flag such grants when the service records a policy delta, and the privileged IAM role granted rules flag basic and IAM administration roles.
To pull the same events on demand, the read-only script below runs gcloud logging read against a project or the organization. It needs Logs Viewer (roles/logging.viewer), plus Private Logs Viewer (roles/logging.privateLogViewer) for the Data Access entries that --with-token-use adds.
#!/usr/bin/env bash
#
# gcp-key-wif-audit-events.sh
#
# Purpose: List recent Cloud Audit Logs events for service account keys,
# service account allow policies, workload identity pools and
# providers, and organization policies. With --with-token-use, also
# list federated token exchanges and short-lived credentials issued
# for service accounts. Prints CSV to standard output.
# Mode: Read-only. Reads log entries with gcloud logging read.
# Auth: roles/logging.viewer for Admin Activity audit logs. --with-token-use
# reads Data Access audit logs and also needs
# roles/logging.privateLogViewer. Those entries exist only after you
# enable Data Access audit logs (Admin Read) for the IAM API and the
# Security Token Service API.
# Where: Cloud Shell or an admin workstation with the Google Cloud CLI.
# Usage: gcp-key-wif-audit-events.sh <projects/ID|organizations/ID> [--freshness <duration>] [--with-token-use]
# Example: gcp-key-wif-audit-events.sh projects/example-project --freshness 30d --with-token-use > key-wif-events.csv
set -euo pipefail
USAGE='usage: gcp-key-wif-audit-events.sh <projects/ID|organizations/ID> [--freshness <duration>] [--with-token-use]'
SCOPE="${1:?$USAGE}"
shift
FRESHNESS="30d"
WITH_TOKEN_USE=false
while [ "$#" -gt 0 ]; do
case "$1" in
--freshness) FRESHNESS="${2:?--freshness needs a duration such as 30d}"; shift 2 ;;
--with-token-use) WITH_TOKEN_USE=true; shift ;;
*) echo "Unknown option: $1" >&2; exit 2 ;;
esac
done
case "$SCOPE" in
projects/*) SCOPE_FLAG=(--project="${SCOPE#projects/}") ;;
organizations/*) SCOPE_FLAG=(--organization="${SCOPE#organizations/}") ;;
*) echo "$USAGE" >&2; exit 2 ;;
esac
command -v gcloud >/dev/null 2>&1 || { echo "The Google Cloud CLI (gcloud) is not installed." >&2; exit 1; }
METHODS='"google.iam.admin.v1.CreateServiceAccountKey" OR "google.iam.admin.v1.UploadServiceAccountKey"'
METHODS+=' OR "google.iam.admin.v1.DisableServiceAccountKey" OR "google.iam.admin.v1.EnableServiceAccountKey"'
METHODS+=' OR "google.iam.admin.v1.DeleteServiceAccountKey" OR "google.iam.admin.v1.SetIAMPolicy"'
METHODS+=' OR "google.iam.v1.WorkloadIdentityPools.CreateWorkloadIdentityPool"'
METHODS+=' OR "google.iam.v1.WorkloadIdentityPools.CreateWorkloadIdentityPoolProvider"'
METHODS+=' OR "google.iam.v1.WorkloadIdentityPools.UpdateWorkloadIdentityPoolProvider"'
METHODS+=' OR "google.iam.v1.WorkloadIdentityPools.DeleteWorkloadIdentityPoolProvider"'
METHODS+=' OR "google.iam.v1.WorkloadIdentityPools.SetIamPolicy"'
METHODS+=' OR "google.cloud.orgpolicy.v2.OrgPolicy.CreatePolicy" OR "google.cloud.orgpolicy.v2.OrgPolicy.UpdatePolicy"'
METHODS+=' OR "google.cloud.orgpolicy.v2.OrgPolicy.DeletePolicy"'
if [ "$WITH_TOKEN_USE" = true ]; then
METHODS+=' OR "google.identity.sts.v1.SecurityTokenService.ExchangeToken" OR "GenerateAccessToken"'
fi
echo 'timestamp,method,principal_email,principal_subject,resource_name'
gcloud logging read "protoPayload.methodName=(${METHODS})" "${SCOPE_FLAG[@]}" \
--freshness="$FRESHNESS" \
--format='csv[no-heading](timestamp,protoPayload.methodName,protoPayload.authenticationInfo.principalEmail,protoPayload.authenticationInfo.principalSubject,protoPayload.resourceName)'
bash gcp-key-wif-audit-events.sh projects/example-project --freshness 30d --with-token-use > key-wif-events.csv
timestamp,method,principal_email,principal_subject,resource_name
2026-11-26T09:40:12.530Z,google.iam.admin.v1.DisableServiceAccountKey,admin@corp.example.com,,projects/example-project/serviceAccounts/ci-deployer@example-project.iam.gserviceaccount.com/keys/0a1b2c3d4e5f60718293a4b5c6d7e8f901234567
2026-11-25T08:15:41.006Z,GenerateAccessToken,,principal://iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/github-pool/subject/repo:example-org/example-repo:ref:refs/heads/main,projects/-/serviceAccounts/100000000000000000001
2026-11-25T08:15:40.118Z,google.identity.sts.v1.SecurityTokenService.ExchangeToken,,repo:example-org/example-repo:ref:refs/heads/main,projects/123456789012/locations/global/workloadIdentityPools/github-pool/providers/github-provider
2026-11-24T10:02:17.412Z,google.iam.v1.WorkloadIdentityPools.CreateWorkloadIdentityPoolProvider,admin@corp.example.com,,projects/example-project/locations/global/workloadIdentityPools/github-pool/providers/github-provider
The filter covers the v1 Workload Identity Pools API and the v2 Organization Policy API; Google also logs v1beta pool methods under their own names. A provider change outside your change window, or a token exchange from a subject you don't recognize, deserves the same response as a new key.
Troubleshooting
Most failures come from a missing permission in the workflow, an attribute condition that doesn't match, or an API that rejects federated tokens.
| Symptom | Cause | Fix |
|---|---|---|
| The auth step can't get a GitHub OIDC token | The job lacks id-token: write |
Add the permissions block at the workflow or job level |
| The token exchange fails right after setup | Pools, providers and IAM permissions can take up to 5 minutes to propagate | Wait five minutes and run the job again |
| The token exchange fails for one repository | The attribute condition doesn't match, or it uses a claim without a mapping | Compare the condition with providers describe and map every claim it uses |
generateAccessToken is denied |
No Workload Identity User binding for this principal set, or the member uses the project ID | Bind the principal set with the project number |
An API returns 401 UNAUTHENTICATED with a federated token |
The API doesn't accept federated access tokens | Use service account impersonation for that API |
Creating a provider fails with FAILED_PRECONDITION and constraints/iam.workloadIdentityPoolProviders |
The organization policy doesn't allow this issuer | Allow the issuer URI in the pool project |
| Later steps can't authenticate | actions/checkout ran after auth |
Move the checkout step before auth |
gsutil ignores the credentials |
gsutil doesn't use the credentials the action exports |
Use gcloud storage |
last_authenticated reads unknown in the inventory |
The Policy Analyzer API is off or the role is missing | Enable the API and grant Activity Analysis Viewer |
| Calls still succeed after a key was deleted | Short-lived credentials issued earlier remain valid | Disable or delete the service account to revoke them |
How Forestall helps
Forestall's GCP scan collects service accounts, service account keys, workload identity pools and workload providers, and its GCP glossary explains that a key inherits its service account's privilege level and that a principal representing an entire pool is treated as Everyone-Like. The IAM Assessment and Tier0 Analysis modules in the GCP scan policy check IAM across organizations, folders and projects and calculate attack paths from Tier 2 identities to Tier 0 assets. Keys appear as the GCP_HAS_SERVICE_ACCOUNT_KEY edge, key creation rights as GCP_CREATE_SA_KEYS, and Workload Identity User bindings for external identities as GCP_FEDERATE_IDENTITY. The non-human and agent identity compromise use case shows how Forestall finds automation identities, maps their reach and prioritizes them by blast radius.
Frequently Asked Questions
What is workload identity federation in Google Cloud?
Workload identity federation in Google Cloud is an IAM feature that lets workloads outside Google Cloud, such as GitHub Actions jobs, AWS or Azure workloads, or applications behind an OIDC or SAML identity provider, access Google Cloud resources without service account keys. The workload exchanges a credential from its own identity provider for a short-lived Google Cloud token, and IAM decides what it can reach through ordinary allow policies.
How does workload identity federation work?
In workload identity federation, the workload gets a token from its identity provider, such as a GitHub Actions OIDC token, and sends it to Google's Security Token Service. A workload identity pool provider checks the issuer and audience, maps the token's claims to Google attributes and evaluates the attribute condition. If the condition passes, the workload receives a federated token and uses it directly on resources or to impersonate a service account.
How do I disable service account key creation in GCP?
Enforce the Disable service account key creation constraint at the root of your Google Cloud organization: iam.managed.disableServiceAccountKeyCreation, or the legacy iam.disableServiceAccountKeyCreation. As of November 2026, organizations created on or after May 3, 2024 have key creation blocked by default. The constraint isn't retroactive, so existing keys keep working until you disable and delete them. You need the Organization Policy Administrator role; Owner and Editor can't change it.
What is the difference between workload identity federation and GCP service account impersonation?
Workload identity federation decides who outside Google Cloud can obtain a federated token; service account impersonation is one way to use that token. With direct resource access, you grant roles to the federated principal on each resource. With impersonation, you grant the federated identity Workload Identity User on a service account and the workload acts as that account. Google recommends direct access, with impersonation as the alternative for APIs that have limitations.
What are the main GCP service account best practices?
Google's main GCP service account best practices are to create single-purpose service accounts, use service account keys only when there is no viable alternative, and stop users from creating or uploading keys. Google also recommends disabling unused service accounts before deleting them, avoiding grants on service accounts at the project or folder level, enabling Data Access logs for IAM APIs and keeping CI/CD history correlated with Cloud Audit Logs.
Can GitHub Actions use workload identity federation without a service account?
Yes, GitHub Actions can use direct resource access: you grant roles to the repository's principal set on each resource and leave out the service_account input of google-github-actions/auth. The README of the action notes that not every Google Cloud resource supports principal set identities, and that generating OAuth 2.0 access tokens or ID tokens still needs a service account. In those cases, grant Workload Identity User on a dedicated service account instead.
Related guides
- Secure GitHub personal access tokens: the GitHub side of the same cleanup, from fine-grained tokens to GitHub Apps and OIDC.
- Move from IAM users to AWS IAM Identity Center: retire long-lived AWS access keys the way this guide retires service account keys.
- Secure MCP server authentication: short-lived, audience-bound tokens for AI tools that call cloud APIs.
- How to secure Active Directory service accounts: the on-premises side of service account hygiene, where Group Managed Service Accounts (gMSA) automate credential management.
- Google Cloud IAM security best practices: where keyless authentication fits in a wider Google Cloud IAM program, alongside workload identities in general.
References
- Workload Identity Federation (Google Cloud)
- Configure Workload Identity Federation with deployment pipelines (Google Cloud)
- Best practices for using Workload Identity Federation (Google Cloud)
- Best practices for managing service account keys (Google Cloud)
- Restrict IAM service account usage (Google Cloud)
- Manage Google Cloud security baseline constraints (Google Cloud)
- View recent usage for service accounts and keys (Google Cloud)
- Identity and Access Management audit logging (Google Cloud)
- Example logs for Workload Identity Federation (Google Cloud)
- Configuring OpenID Connect in Google Cloud Platform (GitHub Docs)
- OpenID Connect reference (GitHub Docs)
- Account Manipulation: Additional Cloud Credentials, T1098.001 (MITRE ATT&CK)
See your identity exposure clearly.
Start with a 1-day Proof of Value in your own environment.