Skip to main content

Securing Service Accounts Without Key Files

Secure GCP service accounts without key files: attach them to VMs and use impersonation for short-lived tokens that cannot leak like JSON keys.

38 Terms

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.

flowchart TD A[Workload needs GCP access] --> B{Where does it run?} B -->|On GCP| C[Attach service account] B -->|Human or CI| D[Impersonate service account] B -->|Outside GCP| E[Workload Identity Federation] C --> F([No key file]) D --> F E --> F classDef decision fill:#F59E0B,color:#111827 classDef safe fill:#10B981,color:#FFFFFF classDef tool fill:#326CE5,color:#FFFFFF class A tool class B decision class C,D,E tool class F safe

Impersonation works in three short steps, and the key never appears:

sequenceDiagram participant U as You participant I as IAM Credentials API participant S as Cloud Storage U->>I: Request token I-->>U: Short-lived token U->>S: List bucket S-->>U: Objects returned

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.

Bash
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_ID
gcloud billing projects link $PROJECT_ID --billing-account=$BILLING_ACCOUNT_ID
gcloud services enable compute.googleapis.com storage.googleapis.com iamcredentials.googleapis.com
How 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.

Bash
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.

Bash
gcloud storage buckets create $BUCKET --location=asia-south1
echo "q3-settlement-report" > report.txt
gcloud 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.

Bash
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-platform
Remember

To 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.

Bash
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 read
gcloud compute ssh vm-app-backend --zone=asia-south1-a \
--command="gcloud storage ls $BUCKET"
# Denied with a 403: objectViewer cannot write
gcloud 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.

Bash
gcloud storage ls $BUCKET --impersonate-service-account=$SA_EMAIL

Grant 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.

Bash
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_EMAIL
Security

gcloud auth print-access-token --impersonate-service-account=$SA_EMAIL prints 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.

Bash
gcloud iam service-accounts keys list --iam-account=$SA_EMAIL --managed-by=user
# Expected: Listed 0 items.
How to Clean Up
Bash
gcloud compute instances delete vm-app-backend --zone=asia-south1-a --quiet
gcloud storage rm -r $BUCKET
gcloud projects delete $PROJECT_ID --quiet

Production Best Practices & Common Pitfalls

Security

Avoid 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.

Tip

If 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 Mistake

Treating --scopes as 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.disableServiceAccountKeyCreation organization policy constraint so keys cannot be created by accident.
  • Treat Token Creator as sensitive. Granting roles/iam.serviceAccountTokenCreator is 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

Resources

Artifact Registry

Google Cloud's current, unified package and container image storage service, the successor to the older Container Registry. It supports container images alongside language packages like npm, Maven, and Python packages in one service, and supports cleanup policies to automatically remove old, untagged image versions.

BigQuery

Google Cloud's serverless data warehouse for analytics, priced based on the volume of data a query actually scans rather than pre-provisioned compute capacity. Selecting only needed columns and querying a properly partitioned table's relevant date range are the two highest-impact levers for controlling BigQuery cost.

Bigtable (GCP)

A wide-column NoSQL database built for very high throughput at extremely low latency, suited to time-series data, IoT telemetry, and analytics workloads with massive write volume. It is a specialized tool distinct from Firestore's document model or Cloud SQL's relational model.

Billing Account (GCP)

A separate object from a Project that holds the actual payment method for Google Cloud usage. One Billing Account can be linked to many Projects, all of whose usage is billed to that same account, letting a company centralize payment while individual Projects retain their own separate IAM control over resources.

Cloud Armor

A security policy service attached to a Global External HTTP(S) Load Balancer, filtering malicious requests before they reach the backend. It supports rate-based rules blocking a single source IP exceeding a request threshold, and preconfigured WAF rules blocking common attack patterns like SQL injection, Google's equivalent of AWS WAF or Azure WAF.

Cloud Functions (GCP)

Google Cloud's event-driven, single-purpose compute service, the most granular and shortest-lived compute unit in GCP's compute spectrum. It fits a narrow niche compared to Cloud Run - a specific triggered action like resizing an uploaded image, rather than a full application with multiple routes and business logic.

Cloud Load Balancing

Google Cloud's family of load balancing products, spanning Global External HTTP(S) Load Balancers (public, distributed globally via a single IP), Regional External Load Balancers, and Internal Load Balancers reachable only from within the VPC. The right type depends on traffic type and whether the backend should ever be reachable from the public internet.

Cloud Logging

Google Cloud's service for collecting, storing, and querying log data from every GCP service and custom applications. Its query filter syntax lets logs be narrowed by resource, severity, and specific field values, and Log Sinks can route matching logs to BigQuery, Cloud Storage, or Pub/Sub for long-term retention beyond the default window.

Cloud Monitoring

Google Cloud's metrics, dashboards, and alerting service. An alert policy requires a Notification Channel explicitly attached to actually notify someone when it fires - without one, the policy still evaluates and logs its own firing history, but nobody is ever told, a common and easy-to-miss misconfiguration.

Cloud NAT

A service providing outbound-only internet connectivity for resources with no external IP address, GCP's equivalent of an AWS or Azure NAT Gateway. Cloud NAT requires a Cloud Router in the same region and provides zero inbound connectivity capability - a resource behind it remains completely unreachable from the internet.

Cloud Run

A fully managed, serverless platform for running containerized applications, scaling automatically to zero when idle and billing only for actual invocations. It combines the flexibility of running any container with zero OS management overhead, making it the right default for a standard stateless containerized web service.

Cloud SQL

Google Cloud's managed relational database service, supporting MySQL, PostgreSQL, and SQL Server. It is the right default for a traditional relational workload with moderate scale needs, handling patching, backups, and replication automatically without requiring OS-level access to the underlying database server.

Cloud Spanner

A globally distributed, strongly consistent relational database offering both SQL semantics and horizontal scalability beyond what a single Cloud SQL instance can provide. It is the right choice specifically when a workload needs both relational query capability and massive scale simultaneously, not simply because a workload feels large or important.

Cloud Storage Bucket

The top-level container for objects in Google Cloud Storage, GCP's object storage service equivalent to AWS S3 or Azure Blob Storage. Every object uploaded to Cloud Storage must belong to exactly one bucket, and bucket-level settings control default storage class, location, and access permissions for everything inside it.

Cloud VPN (GCP)

A service connecting an on-premises network to a GCP VPC over an encrypted tunnel, similar to VPN Gateway in Azure or a Site-to-Site VPN in AWS. It requires a Cloud Router as its foundation and is distinct from VPC Network Peering, which connects two GCP VPCs directly rather than an external network.

Compute Engine

Google Cloud's Infrastructure-as-a-Service offering, providing full virtual machines with complete OS-level control. It is the right choice specifically when a workload needs custom software, specific OS configurations, or hardware-level access that GKE and Cloud Run don't expose.

Error Reporting (GCP)

A Google Cloud operations service that automatically aggregates and groups application errors from logs and instrumented code, surfacing recurring error patterns and their frequency without requiring manual log searching for each individual occurrence.

Firestore

A serverless NoSQL document database built for mobile and web application data, flexible schemas, and real-time client synchronization. It is not a strong fit for workloads needing complex relational joins or multi-row transactions across unrelated entities, which point instead to Cloud SQL or Spanner.

GCP Audit Log

A specific category of Cloud Logging entry recording administrative actions and data access. Admin Activity logs (configuration changes) are always enabled and cannot be disabled; Data Access logs (who read or wrote actual data) are disabled by default for most services and must be explicitly enabled before that history exists.

GCP Firewall Rule

A rule defined at the VPC level controlling inbound or outbound traffic, applied using network tags or Service Accounts on instances rather than being tied to a specific subnet boundary. A firewall rule only affects VMs carrying the exact matching tag or identity - a VM without it is entirely unaffected, silently, with no error to flag the mismatch.

GCP Folder

An optional grouping node in the GCP resource hierarchy, sitting between the Organization and individual Projects. Folders are commonly used to group Projects by team, department, or environment, letting IAM permissions and Organization Policies be applied once at the Folder level rather than repeated across every Project inside it.

GCP IAM Role Types

Google Cloud IAM roles come in three types: Basic roles (Owner, Editor, Viewer) which are broad and legacy; Predefined roles curated by Google and scoped to a specific service's specific needs; and Custom roles built from individual permissions for access needs a predefined role doesn't precisely match.

GCP Organization

The top-level node in Google Cloud's resource hierarchy, tied to a Google Workspace or Cloud Identity domain. An Organization contains Folders and Projects, and policies or IAM permissions set at this level automatically apply to everything beneath it across the entire company.

GCP Project

The fundamental unit of organization in Google Cloud - every resource belongs to exactly one Project, which serves as the boundary for billing, IAM permissions, and API enablement. A Project has a permanent, globally unique Project ID chosen at creation and never changeable, distinct from its display name which can be updated freely.

GCP Quota

A default limit on how much of a specific resource (like VM CPUs or API calls) can be used per Project per region, designed to prevent runaway costs and protect shared infrastructure. Quotas can be checked and increased through the Console ahead of a known future need, such as a planned launch event.

GCP Storage Class

A pricing and access tier for Cloud Storage objects - Standard, Nearline, Coldline, or Archive - trading lower storage cost against higher retrieval cost and a longer minimum storage duration. Deleting or overwriting an object before its class's minimum duration elapses still bills as if it were stored the full minimum period.

GKE Autopilot

A mode of Google Kubernetes Engine where Google manages node provisioning, sizing, and patching entirely - you define workloads, and nodes appear automatically to run them, billed per pod resource request rather than per node. It is the lower-effort default for most containerized workloads, versus Standard mode's direct node pool control.

Managed Instance Group

A group of identical Compute Engine VMs created from an Instance Template and managed as a single unit, GCP's equivalent of an AWS Auto Scaling Group or Azure VM Scale Set. A Managed Instance Group can autoscale based on a metric like CPU utilization, adding or removing instances automatically within configured minimum and maximum bounds.

Network Tag (GCP)

A freeform string label attached to a Compute Engine VM at creation time, used to target firewall rules to specific VMs. Network tags are simple but can be forgotten or misspelled at scale, which is why Service Account-based targeting is often preferred for anything security-critical in a growing fleet.

OS Login

A Compute Engine feature that ties SSH access to a user's actual Google Identity and IAM permissions, rather than manually managing individual SSH public keys per VM. Enabling OS Login means revoking a departing employee's GCP access also immediately revokes their SSH access to every VM, with no separate key cleanup needed.

Organization Policy (GCP)

A constraint applied at the Organization, Folder, or Project level that restricts what resources are allowed to look like across everything beneath that level - for example, blocking external IP addresses on VMs or restricting allowed regions. Unlike IAM, which controls who can act, Organization Policy controls what configurations are permitted.

Persistent Disk (GCP)

The block storage attached to a Compute Engine VM, equivalent to an AWS EBS volume or Azure Managed Disk. Persistent Disks come in zonal (replicated within one zone, lower cost) and regional (synchronously replicated across two zones, survives a single zone failure) variants.

Security Command Center

Google Cloud's security posture management service, continuously scanning deployed resources against security best practices and surfacing specific, severity-ranked findings - like a publicly accessible storage bucket - rather than a single opaque score. Findings should be prioritized by actual severity, not treated as a count to minimize.

Service Account (GCP)

An identity used by applications, VMs, and automated processes to authenticate to Google Cloud APIs, rather than by a human user. A Service Account is itself also a resource with its own IAM permissions, and can be attached directly to a VM or impersonated temporarily, both safer alternatives to downloading its long-lived JSON key file.

Shared VPC

A configuration where one Project (the host) owns a VPC network, while other Projects (service projects) attach to it and deploy resources using its subnets. This centralizes network administration in the host Project while letting individual teams in service Projects still manage their own resources independently.

Spot VM (GCP)

A Compute Engine VM using Google's spare, unused capacity at a steep discount, with the trade-off that Google can reclaim the instance with short notice. Spot VMs are appropriate only for fault-tolerant, interruption-tolerant workloads like batch processing, never for customer-facing services needing reliable availability.

VPC (GCP)

A Virtual Private Cloud in Google Cloud is a global resource by default, unlike the regional VPC or VNet model in AWS or Azure - a single GCP VPC can span every region, with individual subnets defined per-region inside it. The default auto-mode VPC pre-creates a subnet in every region, while a custom-mode VPC starts empty until subnets are deliberately defined.

VPC Network Peering

A direct connection between two separate VPCs, potentially in different Projects or Organizations, with traffic never touching the public internet. Peering must be established from both sides to become active, and is explicitly non-transitive - if VPC A peers with B, and B peers with C, A cannot reach C without its own direct peering connection to C.

Explore More in GCP Fundamentals and Resource Governance

All 6 Topics

Frequently Asked Questions

Is Securing Service Accounts Without Key Files free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Securing Service Accounts Without Key Files topic cover?

Secure GCP service accounts without key files: attach them to VMs and use impersonation for short-lived tokens that cannot leak like JSON keys.

Found a mistake, an outdated step or a broken link?