Tools · Cloud security · 22 / 24
Google Cloud IAM and service account keys: why to avoid them and what to use instead
Understand GCP IAM bindings and basic roles, find long-lived service account keys, and replace them with attached service accounts, impersonation, or Workload Identity Federation.
How GCP IAM is shaped
Google Cloud IAM grants roles to principals through bindings in an allow policy attached to an organization, folder, project, or resource. Policies inherit down the hierarchy. Basic roles (Owner, Editor, Viewer) are very broad and predate fine-grained roles; prefer predefined or custom roles.
Service accounts are identities for workloads. They can be granted roles and can also be resources that others are granted access to, such as roles/iam.serviceAccountUser or roles/iam.serviceAccountTokenCreator, which let a principal act as that service account.
The key problem
A user-managed service account key is a JSON file containing a private key that works from anywhere until it is deleted. Keys leak through source repositories, laptops, and CI logs. Alternatives: attach the service account to the compute resource so it gets short-lived tokens from the metadata server, use impersonation for humans, and use Workload Identity Federation for external systems such as GitHub Actions or AWS.
The organization policy constraint iam.disableServiceAccountKeyCreation blocks new keys. Newer organizations have it enforced by default.
Lab: inventory keys and basic roles
In a sandbox project, list user-managed keys for each service account with their creation dates, and list any principals with basic roles. Delete a test key and confirm it disappears from the list.
for sa in $(gcloud iam service-accounts list --format='value(email)'); do
gcloud iam service-accounts keys list --iam-account="$sa" --managed-by=user \
--format='table(name.basename(),validAfterTime)'
done
gcloud projects get-iam-policy my-lab-project --flatten='bindings[].members' \
--filter='bindings.role:(roles/owner OR roles/editor)' --format='table(bindings.role,bindings.members)'Next steps
Use IAM Recommender to trim unused permissions, and Policy Analyzer to answer “who can access this resource”. Audit Logs record service account key creation and impersonation events.
Diagram
Service account key versus federation
Short-lived beats long-lived.
Lifetime. Until deleted
Where it works. Anywhere the file is copied
Risk. Leaks in repos and logs
Lifetime. Short-lived tokens
Where it works. Only for the trusted external identity
Risk. Much smaller; nothing to leak at rest
Check yourself
1. Which GCP roles are very broad and should be replaced with predefined roles?
2. Which organization policy constraint blocks creation of new service account keys?
3. A GitHub Actions workflow needs to deploy to GCP. What is the preferred credential?