← All articles

GCP Service Account Key Rotation Automation Guide

Two blank ivory cards beside an open teal notebook with an amber bookmark and paper leaves.
A conceptual reminder to review replacement credentials and the services that use them.

Key takeaways

  • GCP user-managed service account keys never expire on their own, so rotation windows of 30 to 90 days must be enforced by your own pipeline.
  • Workloads on GKE, GitHub Actions or cross-cloud OIDC should use workload identity federation instead of user-managed keys, eliminating rotation entirely.
  • A safe rotation pipeline creates the new key, deploys it everywhere, verifies authentication, then deletes the old key by key ID during a 24 to 72 hour overlap.
  • The rotation function needs only roles/iam.serviceAccountKeyAdmin scoped to the project, and should run on a platform service account with no user-managed key of its own.
  • Vaults hold secret values but cannot answer who owns a key or when it expires, which is the gap a metadata-only lifecycle inventory fills.

You can automate GCP service account key rotation end to end with Cloud Scheduler, Cloud Functions and the IAM API, and for most workloads you should first ask whether the keys should exist at all. This guide gives you a copy-adaptable rotation pipeline built on native GCP services, plus a decision framework for when workload identity federation makes rotation unnecessary.

Why do GCP service account keys need rotation at all?

A user-managed service account key is a private key your team downloads and stores. It never expires on its own, it is not covered by Cloud IAM's automatic credential management, and whoever holds the file can authenticate as the service account from anywhere. If it leaks into a Postman collection, a CI log, or a laptop, you have handed out a working identity with no expiry date.

What happens if a leaked key is never rotated

Nothing stops it working. The account keeps its IAM permissions until a human notices, and audit logs only tell you after the fact. Rotation is what bounds that window.

Google's recommended rotation window

Google's IAM documentation advises rotating user-managed keys on a schedule you define, commonly 30 to 90 days, and deleting old keys promptly (Google Cloud IAM docs). Tracking which key is live, who owns it, and when it is due is where lifecycle tooling like KeyGuardRail's terms of use scope begins.

When should you rotate keys versus switch to workload identity federation?

Federate whenever the workload can exchange its own identity for short-lived creds. Rotate user-managed keys only where federation is not yet supported. Everything else is a rotation policy you now have to own: who owns this key, when does it expire, and who gets paged on day 89 of a 90-day window.

Workloads that qualify for federation today

GKE workloads, workloads running on other clouds with OIDC/SAML identity providers, GitHub Actions pipelines, and anything that can present a token from an identity it already trusts. If the runtime can fetch a short-lived token, a user-managed key is a liability with a rotation deadline attached for no benefit.

Cases where a user-managed key is still required

Legacy code that calls Google APIs with a key file and no token exchange path. Third-party SaaS or vendor integrations where you cannot control the runtime. On-prem jobs with no OIDC issuer available. In those cases, automate rotation and track ownership and expiry metadata so the key does not outlive the person who created it.

Decision table: rotate vs federate

SituationChooseWhy
GKE, GitHub Actions, cross-cloud OIDCFederateShort-lived creds, no rotation deadline
Vendor integration you don't controlRotateKey must exist; track owner and expiry
Legacy key-file codeRotate now, federate laterReduce risk while you refactor
Secrets sprawl across Postman and dev toolsInventory firstYou cannot rotate what nobody owns

KeyGuardRail tracks the rotate side: metadata-only lifecycle monitoring, no secret value custody. See our automation access brief.

How do you build an automated rotation pipeline with Cloud Scheduler and Cloud Functions?

Architecture overview

Three components: a Cloud Scheduler job on a cron schedule, a Cloud Function (or Cloud Run job) that runs the rotation logic, and a destination where the new key lands, usually Secrets Manager or Pub/Sub for downstream consumers. The function holds a service account with only iam.serviceAccountKeyAdmin on the target project, so the rotation job itself never needs broad IAM rights. A state record in Firestore or a Secret Manager entry tracks which key version is current and which is pending deletion.

The rotation function, step by step

The flow is four calls to the IAM API. First, projects.serviceAccounts.keys.create generates a new key. Second, the function writes the key material to your vault, which is the only moment the secret moves, and it moves machine to machine. Third, you wait a grace window so workloads pick up the new key. Fourth, projects.serviceAccounts.keys.delete removes the old key by its key ID, not by "latest", because latest may have changed if the job ran twice.

The reason to keep this pipeline dumb is that the hard part is not the API calls. It is knowing, at every moment, which key is current, which is pending, and which workload last fetched the new value. Rotation scripts fail quietly: the create succeeds, the delete never runs, and you accumulate keys until an auditor or an attacker notices. That is why the state record and the delete step are non-negotiable, and why a metadata-only inventory of who owns each key and when it expires belongs outside the script. If you are tracking that by hand today, a dedicated lifecycle layer such as KeyGuardRail or, on GCP specifically, dropping keys for workload identity federation removes the problem class entirely.

Scheduling and grace periods

Run the Scheduler job at 30/60/90 day intervals to match your rotation policy, and set the grace period to your longest consumer's cache or cold-start window, often 24 to 48 hours. Encode the deadline in the state record so a failed delete shows up as a stale pending key you can alert on, rather than a silent accumulation.

How do you rotate a service account key without breaking running workloads?

Downtime during rotation almost always comes from deleting the old key before every workload has the new one. The safe ordering is: create the new key, deploy it everywhere the old key is used, verify the new key authenticates, then delete the old key. Never reverse steps two and three.

Overlap window design

Keep both keys valid during the overlap. GCP allows up to 10 keys per service account, so a two-key overlap is cheap. A practical window is 24 to 72 hours: long enough to cover staging canaries and a full deploy cycle, short enough that a leaked old key has limited life. Treat the overlap as an explicit deadline, not an indefinite state. If your rotation policy follows a 30/60/90 day pattern, bake the overlap length into it the same way you would for any API key expiry schedule (https://keyguardrail.com/blog/api-key-expiration-policy-examples).

Where the new key lands: Secret Manager vs workload config

Deliver the new key into Secret Manager and have workloads read it at startup or via a mounted version, rather than editing env files or Postman collections by hand. Human transport is where rotations break. Pin each workload to the secret version, verify with a test call using the new key, then delete the old key and record who owned the change.

What IAM API permissions does an automated rotation job need?

Required roles at project and org level

Grant the rotation function's service account roles/iam.serviceAccountKeyAdmin at the project level, scoped to the projects where keys live. That role covers iam.serviceAccountKeys.create and iam.serviceAccountKeys.delete, the two methods the Google Cloud IAM API reference documents for key lifecycle calls. Do not grant org-level roles unless the job rotates keys across projects; a project-scoped binding keeps the blast radius of a compromised function to one project.

Hardening the rotation identity itself

Skip user-managed keys for the rotation identity entirely: run the Cloud Function with its default service account and rely on the platform's short-lived credentials, so the rotation job itself has nothing to leak. Add a condition to the role binding limiting it to service accounts tagged for rotation, and log every create/delete call to Cloud Audit Logs. Track which engineer owns that identity and when its access was last reviewed, the same expiry metadata you apply to any other credential; a registry like KeyGuardRail's deletion and lifecycle records keeps that audit trail without holding secret values.

How do you verify old keys are revoked after automated rotation?

Listing keys and comparing key IDs

After each rotation run, call projects.serviceAccounts.keys.list and diff the returned key IDs against the set your job recorded before rotation. The old key ID should be absent and a new one present. Store that diff as an artifact from the pipeline so you have an audit trail of what was deleted and when, not just a success flag. If the old key ID still appears, treat the rotation as failed and page the owner rather than retrying silently.

Audit log checks for key deletions

The list call tells you current state; audit logs tell you history. Query Cloud Audit Logs for google.iam.admin.v1.DeleteServiceAccountKey entries and confirm one exists per rotation, timestamped after the new key was created. This also catches keys that escaped the job entirely: any CreateServiceAccountKey event from a human principal outside your pipeline is a key your rotation schedule does not own, and it will never expire on its own. Alert on those creations so the owner is identified and the key is either enrolled in rotation or deleted.

How do you monitor rotation failures and alert on stale keys?

A rotation job that exits 0 but creates no key is worse than one that crashes loudly. Alert on three signals: Cloud Scheduler AcquiredLease misses or failed runs, Cloud Function execution errors and timeout counts in Cloud Monitoring, and age of the newest key per service account. A metric like seconds since last successful rotation, exported from the function itself, catches silent failures that log-based alerts miss.

Alerting on Scheduler and Function failures

Set a policy that pages when any service account key exceeds your rotation window (30/60/90 days) plus a grace buffer. The rotation job needs roles/iam.serviceAccountKeyAdmin (or the narrower iam.serviceAccountKeys create/delete permissions), per the Google Cloud IAM roles reference. Grant that role to the function's service account only, and alert on SetIamPolicy denials, which usually mean the job lost permissions mid-run.

Tracking ownership and expiry across providers

GCP alerts won't cover Stripe or GitHub keys, so keep a metadata-only inventory: owner, provider, expiry, last rotation. KeyGuardRail does exactly this without holding secret values, so when a rotation fails, the alert routes to the named owner instead of a shared channel.

Where does lifecycle tracking fit alongside your vault?

Vault custody vs lifecycle coordination

Your vault solves custody: Secret Manager, HashiCorp Vault or Infisical hold secret values and gate access. Neither answers who owns a key, when it expires, or whether the 90-day rotation deadline slipped last quarter. A vault also cannot see keys that never entered it, like the Stripe key sitting in a Postman collection or the GitHub token a departed dev configured by hand.

KeyGuardRail is a metadata-only lifecycle layer. It tracks ownership, expiry dates and rotation deadlines across AWS, GCP and SaaS providers without ever holding the secret value. Your vault stays the system of record for values; KeyGuardRail tells you which credentials are stale, unowned or overdue, and who to ping.

Running the same criteria against KeyGuardRail honestly

Honest scoring against the same tests: KeyGuardRail does not store or rotate secret values, so it complements rather than replaces Doppler, Vault or Infisical. Its fit is the coordination gap: "who owns this key" and "when does it expire" for credentials spread across vaults, IAM and SaaS dashboards. If your sprawl is fully eliminated and every credential is short-lived, you may not need it. If humans are still the transport layer for some keys, that inventory is the piece your vault is missing.

FAQ

Can GCP rotate service account keys automatically without Cloud Functions?

No. Cloud IAM has no built-in scheduler for user-managed keys, so you need something to trigger the rotation: Cloud Scheduler calling a Cloud Function or Cloud Run job is the standard pattern. Alternatively, use workload identity federation where supported, which removes user-managed keys and the rotation problem entirely.

How long is a GCP service account key valid before it expires?

Indefinitely. A user-managed service account key never expires on its own and is not covered by IAM's automatic credential management. Google's documentation advises rotating on a schedule you define, commonly 30 to 90 days, and deleting old keys promptly. Expiry only exists if your pipeline enforces it.

Is it safe to disable service account key creation org-wide and use federation only?

Not usually. GKE workloads, GitHub Actions pipelines and cross-cloud OIDC workloads federate cleanly, but legacy key-file code, vendor SaaS integrations and on-prem jobs with no OIDC issuer still require user-managed keys. Disable creation only after inventorying every key, federating what qualifies, and automating rotation for the remainder.

What's the best 30/60/90 day rotation policy for service account keys in GCP?

Match the interval to key blast radius: 30 days for keys with broad permissions or third-party exposure, 90 days for low-risk internal jobs. Add a 24 to 72 hour overlap window so both keys stay valid during deployment, encode the deadline in your state record, and page the owner when a key exceeds the window plus grace buffer.

How do I find who owns a service account key before I rotate it?

GCP gives you no ownership metadata, so check audit logs for the original CreateServiceAccountKey event, then fall back to internal records. If neither resolves it, treat the key as unowned: alert on it, enroll it in rotation or delete it. A metadata-only inventory prevents this gap from recurring.