Overview and What You Will Learn
A service account is a non-human identity for applications and infrastructure, and a downloaded JSON key file is the riskiest way to use one. Attaching the account to a VM and using impersonation both avoid keys entirely.
In this lab, you will:
- Create a service account and grant it access to one bucket only
- Attach it to a VM so the VM authenticates with no key
- Use impersonation to run commands as the account from your own session
- Audit the account to prove no user-managed key exists
Why This Matters in Production
Long-lived key files are the most common way service account credentials leak. Picture a developer at a payments company like Stripe downloading a key to test locally and committing it to a repository by accident. That key never expires on its own and stays a fully working credential until someone notices and revokes it. Both patterns in this lab remove the need to ever create that file.
Core Principles
GCP offers safer alternatives to key files. Attaching a service account to a VM lets the VM fetch short-lived tokens from the metadata server automatically. Impersonation lets an already-authenticated user or service account temporarily act as another service account, using a token that expires after one hour by default.
Impersonation works in three short steps, and the key never appears:
Detailed Step-by-Step Practical Lab
How to Create the Project and Enable the Required APIs
Impersonation needs the IAM Service Account Credentials API, so enable it alongside Compute Engine and Cloud Storage. Billing must be linked before Compute Engine can be enabled. Use your own Billing Account ID.
export PROJECT_ID="gcp-sa-lab-mumbai-2026"export BILLING_ACCOUNT_ID="0X0X0X-0X0X0X-0X0X0X"export SA_EMAIL="app-backend-sa@${PROJECT_ID}.iam.gserviceaccount.com"export BUCKET="gs://${PROJECT_ID}-reports" gcloud projects create $PROJECT_ID --name="Service Account Lab"gcloud config set project $PROJECT_IDgcloud billing projects link $PROJECT_ID --billing-account=$BILLING_ACCOUNT_IDgcloud services enable compute.googleapis.com storage.googleapis.com iamcredentials.googleapis.comHow to Create a Service Account Without a Key File
Creating a service account does not create a key. Nothing is downloaded, and nothing can leak.
gcloud iam service-accounts create app-backend-sa \ --display-name="Application Backend Service Account"How to Grant a Least-Privilege Role on a Single Bucket
Create a bucket with a sample report, then grant read access on that bucket only. Granting the role on the bucket instead of the whole project keeps the blast radius small.
gcloud storage buckets create $BUCKET --location=asia-south1echo "q3-settlement-report" > report.txtgcloud storage cp report.txt $BUCKET/ gcloud storage buckets add-iam-policy-binding $BUCKET \ --member="serviceAccount:${SA_EMAIL}" \ --role="roles/storage.objectViewer"How to Attach a Service Account to a VM
Attaching the service account at creation time means the VM authenticates as that identity automatically. The cloud-platform scope is deliberately broad, because the IAM role above is what actually limits access.
gcloud compute instances create vm-app-backend \ --zone=asia-south1-a \ --machine-type=e2-medium \ --image-family=debian-12 \ --image-project=debian-cloud \ --service-account=$SA_EMAIL \ --scopes=cloud-platformRememberTo attach a service account, your own user needs the Service Account User role (
roles/iam.serviceAccountUser) on it. Project Owners already have this, but a developer account with narrower access may not.
How to Verify the VM Uses Its Attached Identity
Run commands on the VM and prove it works with no credential file present. Reading succeeds because of the role you granted, and writing fails because you did not grant one.
gcloud compute ssh vm-app-backend --zone=asia-south1-a \ --command='curl -s -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/email' # Allowed: objectViewer can readgcloud compute ssh vm-app-backend --zone=asia-south1-a \ --command="gcloud storage ls $BUCKET" # Denied with a 403: objectViewer cannot writegcloud compute ssh vm-app-backend --zone=asia-south1-a \ --command="gcloud storage cp /etc/hostname $BUCKET/test.txt"How to Impersonate a Service Account with gcloud
From Cloud Shell, run a command as the service account. Impersonation is itself controlled by IAM, and a user with narrow access fails with a 403 on iam.serviceAccounts.getAccessToken until granted the right role. As the project creator you may already be a Project Owner, in which case the first attempt can succeed without the explicit grant.
gcloud storage ls $BUCKET --impersonate-service-account=$SA_EMAILGrant your own user the Service Account Token Creator role on this one service account, wait about a minute for the change to propagate, and retry. This is the least-privilege way to allow impersonation.
gcloud iam service-accounts add-iam-policy-binding $SA_EMAIL \ --member="user:rahul@devops.in" \ --role="roles/iam.serviceAccountTokenCreator" gcloud storage ls $BUCKET --impersonate-service-account=$SA_EMAILSecurity
gcloud auth print-access-token --impersonate-service-account=$SA_EMAILprints a live credential that is valid for about an hour. Use it for demonstrations only, and never paste it into chat, tickets, or logs.
How to Audit for User-Managed Keys
List the keys that humans created for this service account. A clean result proves neither pattern needed one.
gcloud iam service-accounts keys list --iam-account=$SA_EMAIL --managed-by=user# Expected: Listed 0 items.How to Clean Up
gcloud compute instances delete vm-app-backend --zone=asia-south1-a --quietgcloud storage rm -r $BUCKETgcloud projects delete $PROJECT_ID --quietProduction Best Practices & Common Pitfalls
SecurityAvoid downloading service account keys whenever a safer option exists. A key file is a long-lived credential that does not expire on its own and can leak exactly like an AWS access key or an Azure service principal secret.
TipIf a key must exist for a workload outside GCP, such as a script on a laptop or a server in another cloud, first consider Workload Identity Federation. If a key is still unavoidable, store it in Secret Manager instead of a local file and rotate it on a fixed schedule.
Common MistakeTreating
--scopesas the permission boundary. Scopes only cap what the VM may attempt, while the IAM role bindings decide what actually succeeds, and both must allow a call for it to work.
- Create one service account per workload. A shared account means a leak in one application exposes every other application using it.
- Avoid the default Compute Engine service account. It historically carries the broad Editor role, so create a dedicated account with a narrow role instead.
- Block key creation by policy. Enforce the
iam.disableServiceAccountKeyCreationorganization policy constraint so keys cannot be created by accident. - Treat Token Creator as sensitive. Granting
roles/iam.serviceAccountTokenCreatoris equivalent to granting every permission the impersonated account holds.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
gcloud iam service-accounts create NAME |
Create a service account with no key |
gcloud compute instances create --service-account=EMAIL |
Attach a service account to a VM |
gcloud storage ls BUCKET --impersonate-service-account=EMAIL |
Run one command as a service account |
gcloud iam service-accounts add-iam-policy-binding |
Grant permission to impersonate or use an account |
gcloud iam service-accounts keys list --managed-by=user |
Find user-created keys that should not exist |
gcloud services enable iamcredentials.googleapis.com |
Fix impersonation errors caused by a disabled API |