ACEChapter 95 of 101Objective 5.1

Service Account Key Management

This chapter covers service account key management in Google Cloud, a critical security topic for the ACE exam. You'll learn how to create, manage, and secure service account keys, including best practices for avoiding long-lived keys and using alternatives like workload identity federation. Approximately 10-15% of exam questions on security and compliance touch on service account key management, making it essential to understand the mechanisms and common pitfalls.

25 min read
Intermediate
Updated May 31, 2026

Service Account Key as a Secure Proxy Badge

Imagine a large office building with a strict security policy: no external visitors can enter without a temporary badge issued by a front-desk kiosk. However, the building also hosts a sensitive server room that requires a separate, permanent access card. The server room's access card is like a service account key — it's a long-lived credential that directly unlocks a resource. Now, consider a scenario where a delivery person needs to drop off packages to the server room daily. Instead of giving them the permanent access card (which would be risky if lost or copied), the building manager issues a temporary badge that can be revoked after each delivery. This temporary badge is like a short-lived, automatically rotated credential. The manager can also set the badge to expire after one day, and the badge's ID is logged every time it's used. The key management system for service accounts works similarly: you should avoid creating long-lived, downloadable keys (like the permanent card) and instead use workload identity federation or short-lived credentials that are automatically rotated and have limited scope. If a key is compromised, the damage is controlled because the key expires quickly and can be revoked without affecting other services.

How It Actually Works

What is a Service Account Key and Why Does It Exist?

A service account is a special type of Google account intended for non-human users, such as applications or virtual machines (VMs). To authenticate these applications to Google Cloud APIs, you need credentials. Service account keys come in two flavors: Google-managed keys and user-managed keys. Google-managed keys are automatically rotated and can't be downloaded; they are used by Google Cloud services (e.g., Compute Engine default service account). User-managed keys are RSA private keys that you create and download; these are long-lived and pose a security risk if not handled properly.

How Service Account Key Authentication Works Internally

When an application uses a user-managed key to authenticate, it performs a JSON Web Token (JWT) exchange with Google's OAuth 2.0 token endpoint. The application constructs a signed JWT containing the service account email and the desired scope (e.g., https://www.googleapis.com/auth/cloud-platform). This JWT is signed using the private key portion of the service account key. The signed JWT is then sent to https://oauth2.googleapis.com/token, which returns an access token. The access token is then used in API calls as a Bearer token in the Authorization header. The private key never leaves the application's control, but if compromised, an attacker can generate tokens until the key is deleted or rotated.

Key Components, Values, Defaults, and Timers

Key types: JSON and P12. JSON is preferred because it's easier to use with client libraries.

Key creation: You can create up to 10 user-managed keys per service account (default quota).

Key deletion: Deleting a key immediately invalidates it. There is no grace period.

Key rotation: User-managed keys do not auto-rotate. You must manually create a new key, update your application, and delete the old key.

Key expiration: You can set an expiration time when creating a key (max 10 years). After expiration, the key becomes invalid.

Service account impersonation: Short-lived credentials can be generated via the iamcredentials API, with a maximum lifetime of 1 hour for access tokens and 12 hours for ID tokens.

Workload Identity Federation: Allows you to use external identity providers (e.g., AWS, Azure AD) to impersonate a service account without downloading keys.

Configuration and Verification Commands

To create a user-managed key:

gcloud iam service-accounts keys create key.json --iam-account=my-sa@project.iam.gserviceaccount.com

To list keys for a service account:

gcloud iam service-accounts keys list --iam-account=my-sa@project.iam.gserviceaccount.com

To delete a key:

gcloud iam service-accounts keys delete KEY_ID --iam-account=my-sa@project.iam.gserviceaccount.com

To disable a key (prevent use without deleting):

gcloud iam service-accounts keys disable KEY_ID --iam-account=my-sa@project.iam.gserviceaccount.com

To enable a disabled key:

gcloud iam service-accounts keys enable KEY_ID --iam-account=my-sa@project.iam.gserviceaccount.com

To generate a short-lived access token using the iamcredentials API:

gcloud auth print-access-token --impersonate-service-account=my-sa@project.iam.gserviceaccount.com

How Service Account Keys Interact with Related Technologies

IAM roles: The iam.serviceAccountKeyAdmin role allows managing keys; iam.serviceAccountTokenCreator allows generating access tokens via impersonation.

Secret Manager: Store user-managed keys as secrets to avoid hardcoding them in code. Secret Manager can automatically rotate secrets.

Workload Identity Federation: Instead of downloading keys, you configure an external identity provider (e.g., AWS IAM) to exchange tokens for Google Cloud access tokens. This eliminates the need for long-lived keys.

Compute Engine: The default service account has Google-managed keys; you can attach custom service accounts with user-managed keys, but it's discouraged.

Cloud KMS: You can use Cloud KMS to encrypt service account keys at rest, but the keys still exist as plaintext in memory.

Best Practices for Key Management

Avoid creating user-managed keys whenever possible. Use Google-managed keys or workload identity federation.

If you must use user-managed keys, rotate them regularly. The recommended rotation period is every 90 days or less.

Use Secret Manager or Cloud KMS to store keys. Never hardcode keys in source code or environment variables.

Set expiration dates on keys. This forces rotation and limits the window of compromise.

Monitor key usage via Cloud Audit Logs. Look for google.iam.admin.v1.CreateServiceAccountKey and google.iam.admin.v1.DeleteServiceAccountKey events.

Disable unused keys. Disabling a key prevents use without deleting it, allowing recovery if needed.

Limit the number of keys per service account. The default quota is 10; request an increase only if necessary.

Common Pitfalls and How to Avoid Them

Hardcoding keys in code: Use environment variables or secret managers.

Committing keys to source control: Add *.json and *.p12 to .gitignore. Use tools like git-secrets to scan for keys.

Sharing keys across environments: Use separate service accounts for dev, staging, and production.

Forgetting to rotate keys: Implement automated rotation scripts using Cloud Scheduler and Cloud Functions.

Overly permissive roles: Grant only the minimum necessary roles (e.g., roles/iam.serviceAccountUser for impersonation, not roles/owner).

Walk-Through

1

Create a Service Account Key

Navigate to IAM & Admin > Service Accounts in the Google Cloud Console, select a service account, click 'Keys', then 'Add Key' > 'Create New Key'. Choose JSON format. The private key is downloaded immediately. This key is a long-lived credential that never expires unless you set an expiration time during creation. The key consists of a private key (RSA 2048-bit) and associated metadata (service account email, private key ID). The private key ID is a unique identifier used in the JWT header. After download, the key is no longer stored in Google Cloud; you are responsible for its security.

2

Authenticate an Application Using the Key

The application reads the JSON key file and constructs a JWT. The JWT header contains: `{"alg":"RS256","typ":"JWT","kid":"private_key_id"}`. The payload includes: `iss` (service account email), `sub` (same email), `aud` (https://oauth2.googleapis.com/token), `iat` (issued at time in seconds), `exp` (expiration time, usually 3600 seconds later). The JWT is signed with the private key. The signed JWT is sent via HTTP POST to the token endpoint. The response contains an access token (OAuth 2.0) valid for 1 hour by default. The access token is then used for subsequent API calls.

3

Rotate the Service Account Key

To rotate, create a new key for the same service account. This key will have a different private key ID. Update your application to use the new key. Verify the application works with the new key. Then delete the old key. During the transition period, you may have two active keys. The old key remains valid until deleted. If you delete the old key before updating the application, authentication will fail. The recommended rotation period is 90 days. Use Cloud Scheduler to trigger a Cloud Function that automates key creation, updates a secret in Secret Manager, and deletes the old key after a grace period.

4

Revoke a Compromised Key

If you suspect a key is compromised, immediately delete the key using `gcloud iam service-accounts keys delete`. Deletion is irreversible and immediate. There is no revocation list; once deleted, the key cannot be used to obtain new access tokens. However, any access tokens already issued remain valid until they expire (up to 1 hour). To mitigate this, you can also revoke the service account's roles temporarily (remove IAM bindings) or disable the service account entirely. After resolving the compromise, create a new key and update your application.

5

Use Workload Identity Federation Instead

Configure an external identity provider (e.g., AWS IAM, Azure AD, or any OIDC provider) to impersonate a service account. In the Google Cloud Console, go to IAM > Workload Identity Federation, create a pool, and add a provider. Map attributes from the external token to Google Cloud attributes. Grant the `roles/iam.workloadIdentityUser` role to the principal. Your external application then exchanges its native token for a Google Cloud access token via the `sts.googleapis.com` token exchange service. This process eliminates the need for long-lived keys and reduces the attack surface.

What This Looks Like on the Job

Enterprise Scenarios

Scenario 1: CI/CD Pipeline Authentication A large enterprise uses Jenkins to deploy applications to Google Kubernetes Engine (GKE). The Jenkins pipeline needs to authenticate to GKE to apply Kubernetes manifests. Instead of storing a long-lived service account key in Jenkins credentials, the team uses Workload Identity Federation with GitHub Actions. They configure a workload identity pool that trusts tokens issued by GitHub's OIDC provider. The pipeline obtains a short-lived token from GitHub, which is then exchanged for a Google Cloud access token. This eliminates the need to manage static keys. The team also implements automatic key rotation for the service account used by Jenkins itself (if keys are unavoidable). They set up Cloud Scheduler to run a Cloud Function every 30 days that creates a new key, updates the secret in Secret Manager, and deletes the old key after a 24-hour overlap period.

Scenario 2: Third-Party Application Integration A company uses a third-party SaaS application that requires a service account key to access their Google Cloud Storage bucket. The third-party vendor insists on a JSON key file. The company creates a dedicated service account with minimal permissions (only read access to the specific bucket) and sets the key to expire in 1 year. They store the key in Secret Manager and use a VPC Service Control perimeter to restrict access to the key. They also enable Cloud Audit Logs for key usage and set up alerts for any key creation or deletion events. When the key approaches expiration, they rotate it manually and provide the new key to the vendor. The company learned from a previous incident where a key was accidentally committed to a public GitHub repository; they now use git-secrets and automated scanning to prevent recurrence.

Scenario 3: Multi-Cloud Architecture A company runs workloads on both AWS and Google Cloud. They use AWS Lambda functions to write data to Google Cloud BigQuery. Instead of storing a service account key in AWS Secrets Manager, they use Workload Identity Federation with AWS as the external identity provider. The Lambda function assumes an IAM role that is trusted by Google Cloud's workload identity pool. The function exchanges the AWS STS token for a Google Cloud access token. This setup provides cross-cloud authentication without long-lived keys. The team monitors token exchange logs in both clouds to detect anomalies. The main challenge was configuring the attribute mapping correctly; they had to ensure the sub claim from AWS matched the expected format in Google Cloud.

How ACE Actually Tests This

What the ACE Exam Tests

Objective 5.1: "Manage service account key lifecycle" – creation, rotation, deletion, and disabling.

Objective 5.2: "Implement least privilege for service accounts" – granting minimal roles, using custom roles.

Objective 5.3: "Use workload identity federation" – understanding when to use it vs. keys.

Common Wrong Answers and Why Candidates Choose Them

1.

"Service account keys can be rotated automatically by Google Cloud." – This is false. Only Google-managed keys auto-rotate. User-managed keys require manual or scripted rotation. Candidates confuse the two types.

2.

"Deleting a service account key immediately revokes all access tokens issued with that key." – False. Existing access tokens remain valid until they expire (up to 1 hour). Candidates think deletion is instantaneous for all tokens.

3.

"You can use a service account key to authenticate to the Google Cloud Console." – False. Service account keys are for programmatic access only, not for interactive login. Candidates think keys can be used anywhere.

4.

"The maximum number of user-managed keys per service account is 100." – False. The default quota is 10. Candidates misremember or confuse with other quotas.

Specific Numbers and Terms to Memorize

Default quota: 10 user-managed keys per service account.

Maximum key expiration: 10 years.

Access token lifetime: 1 hour (for OAuth 2.0 tokens from JWT exchange).

Short-lived token max lifetime: 1 hour (access token), 12 hours (ID token) via iamcredentials API.

Key formats: JSON and P12.

IAM roles: roles/iam.serviceAccountKeyAdmin (manage keys), roles/iam.serviceAccountTokenCreator (impersonate).

Edge Cases and Exceptions

Disabled keys: A disabled key cannot be used to generate new tokens, but it still counts toward the quota. You can re-enable it.

Key deletion and service account deletion: If you delete a service account, all its keys are automatically deleted. Recreating the service account with the same email does not restore keys.

Cross-project keys: You can use a key from a service account in one project to authenticate to resources in another project, as long as the service account has appropriate IAM permissions on the target project. This is often tested.

How to Eliminate Wrong Answers

If an answer mentions "automatic rotation" for user-managed keys, it's wrong.

If an answer claims keys can be used for console login, it's wrong.

If an answer says deleting a key revokes existing tokens, it's wrong.

If an answer suggests using keys when workload identity federation is possible, it's not the best practice.

Key Takeaways

User-managed service account keys are long-lived credentials that should be avoided; prefer Google-managed keys or workload identity federation.

Default quota is 10 user-managed keys per service account; maximum key expiration is 10 years.

Access tokens obtained from a key are valid for 1 hour; deleting the key does not revoke existing tokens.

Key rotation is manual for user-managed keys; automate using Cloud Scheduler and Cloud Functions.

Workload Identity Federation allows authentication without keys by exchanging tokens from external identity providers.

Store keys in Secret Manager; never hardcode in source code or environment variables.

IAM roles for key management: `roles/iam.serviceAccountKeyAdmin` and `roles/iam.serviceAccountTokenCreator`.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

User-Managed Keys

Long-lived credentials (up to 10 years).

Requires manual rotation and secure storage.

Risk of key exposure if compromised.

Simple to implement with client libraries.

Counts toward key quota (10 per service account).

Workload Identity Federation

No long-lived secrets; uses short-lived tokens.

No manual rotation; tokens are ephemeral.

Eliminates key exposure risk.

Requires configuration of external identity provider.

No key quota; uses IAM policies for access.

Watch Out for These

Mistake

Service account keys are automatically rotated by Google Cloud.

Correct

Only Google-managed keys (used by Google Cloud services like Compute Engine default service account) are automatically rotated. User-managed keys require manual or scripted rotation.

Mistake

You can use a service account key to log into the Google Cloud Console.

Correct

Service account keys are for programmatic API access only. You cannot use them for interactive login. Use gcloud auth login or OAuth 2.0 for user accounts.

Mistake

Deleting a service account key immediately revokes all access tokens issued with that key.

Correct

Deleting a key prevents new tokens from being issued, but existing access tokens remain valid until they expire (up to 1 hour). To immediately revoke access, you must also revoke the service account's roles or disable the service account.

Mistake

You can have up to 100 user-managed keys per service account.

Correct

The default quota is 10 user-managed keys per service account. You can request an increase, but 10 is the standard limit.

Mistake

Service account keys stored in Secret Manager are automatically rotated.

Correct

Secret Manager can store secrets, but it does not automatically rotate service account keys. You must implement rotation logic (e.g., via Cloud Scheduler and Cloud Functions) and update the secret version.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

How do I rotate a service account key without downtime?

Create a new key for the same service account, update your application to use the new key, verify it works, then delete the old key. During the transition, both keys are active. Automate this process with Cloud Scheduler and a Cloud Function that updates a secret in Secret Manager.

Can I use the same service account key in multiple projects?

Yes, a service account key is tied to the service account, not the project. The service account can be granted IAM roles in other projects, and the key can authenticate to those projects. However, this is not recommended due to security concerns; use separate service accounts per project.

What happens if I delete a service account that has keys?

All keys associated with that service account are automatically deleted. You cannot recover them. If you recreate the service account with the same email, you must create new keys.

How long are access tokens valid when using a service account key?

Access tokens obtained via the JWT exchange are valid for 1 hour by default. You can request a shorter lifetime (minimum 10 minutes) but not longer. ID tokens obtained via iamcredentials API can be valid up to 12 hours.

What is the difference between disabling and deleting a service account key?

Disabling a key prevents it from being used to generate new tokens, but it still counts toward the quota and can be re-enabled. Deleting a key is permanent and removes it from the quota.

Can I use a service account key with gcloud?

Yes, use `gcloud auth activate-service-account --key-file=key.json` to authenticate. This is commonly used in CI/CD pipelines.

Is it safe to store service account keys in environment variables?

No, environment variables can be exposed in process listings, logs, or debugging output. Use Secret Manager or a secrets vault instead.

Terms Worth Knowing

Ready to put this to the test?

You've just covered Service Account Key Management — now see how well it sticks with free ACE practice questions. Full explanations included, no account needed.

Done with this chapter?