Home› Blog› Week 9 — Service Account Lifecycle and Unused Iden…
GCP Weekly Lab GCP Terraform

Service account lifecycle and unused identities

Find every machine identity in an organization, prove which have never been used, and close them in the reversible direction.

Verified against current vendor documentation on 16 October 2026. Pricing, limits and API behaviour were checked against the official docs on that date. Cloud services change fast — if you are reading this much later, treat the specifics as a starting point and re-check the linked sources.
GCP Platform Engineering Lab · Week 9 of 58

Lab Overview

The problem. Every project in Google Cloud is created with a service account attached. You do not ask for it, you are not told about it, and it persists for as long as the project does. An unused credential is not dramatic — it is a door nobody checks, in a building where everything else is locked.

Objective. Enumerate every machine identity in the organization, determine which have never authenticated, and disable those without breaking anything that is still in use.

Expected outcome. Unused default service accounts disabled rather than deleted, key creation blocked on both generations of the relevant organization policy constraint, and evidence that the accounts left enabled are the ones actually in use.

DifficultyIntermediate — the deployment is trivial; knowing which accounts are safe to touch is the lab
DeploymentTerraform via HCP Terraform remote execution, Workload Identity Federation, no service account keys
Reproduce itLab guide — the usage query, commands, expected outputs, cleanup
Cost$0 — nothing here runs

Cloud Services and Concepts

ServicePurpose hereWhat it is
IAM service accountsThe identities this week inventories and prunesThe identities being audited. An identity for software: an email address, no password, and permissions attached as they would be to a person.
Default service accountsCreated automatically, used by nothing, disabled hereThe subjects. Google creates one per project so a virtual machine has something to run as before you configure anything.
Activity AnalyzerMeasures which accounts have actually authenticatedAnswers when an identity last authenticated. This is the evidence the whole lab turns on.
Organization PolicyBlocks key creation on both constraint generationsBlocks service account key creation — on both constraint generations, for reasons in Troubleshooting.
Resource ManagerScopes the audit to the projects in the hierarchyEnumerates every project, so the key sweep covers the organization rather than the projects you remembered.

Two concepts worth having before the rest. "Last authenticated" is not "last modified" or "looks quiet" — it is a record of the identity proving who it was. An account silent for a month might be seasonal; an account that has never authenticated has never done anything at all, which is a far safer thing to act on. And constraint generations: the same organization policy rule can exist under an older name and a newer managed one, enforced under one and simply absent under the other — and absent reads identically to switched off.

Architecture and Workflow

Every service account in scope measured with Activity Analyzer for real authentication, then the ones that have never authenticated and hold no role are disabled rather than deleted, with key creation blocked by organization policy.
Measurement comes first and the last step is reversible. Delete is absent from this diagram deliberately.

The flow

  1. Enumerate every service account across every project in the organization.
  2. Ask Activity Analyzer when each last authenticated.
  3. Separate "never authenticated" from "quiet lately" — only the first is safe to act on.
  4. For the never-used accounts, confirm they hold no role anywhere.
  5. Disable them with Terraform, with a restore policy, so the change is reversible.
  6. Close the key-creation constraint on both generations, and re-run the previous weeks' validators to confirm nothing broke.

Two decisions worth naming

Disable, never delete — and not for the reason people assume. The email of a deleted service account can be reused, but IAM tracks an internal unique ID, so role bindings that referred to the deleted account never apply to a recreated one at the same address.

Act on "never", not on "quiet". One account in this organization looked dormant and had authenticated five days earlier. The decision rule is deliberately narrow because the measurement is the only thing making it safe.

Prerequisites

  • An organization with at least two projects that have the Compute Engine API enabled, so default service accounts exist to audit.
  • roles/iam.serviceAccountAdmin and roles/orgpolicy.policyAdmin at the organization, on the Terraform apply identity.
  • Permission to read last-authentication data — roles/iam.securityReviewer or equivalent.
  • policyanalyzer.googleapis.com and orgpolicy.googleapis.com enabled on the quota project.
  • Terraform 1.9+ with hashicorp/google ~> 6.0.

Week 1 supplies the projects whose default accounts are audited here. Exact permissions, variables and commands are in the lab guide.

Implementation

Three resources. The deployment is the small part — knowing which accounts are safe to disable is the lab. Commands and expected outputs are in the lab guide.

Repository structure: LAB.md, terraform, scripts and docs, each with a one-line responsibility.
How the week is organised. Full source on GitHub.

Step 1 — Ask which accounts have ever been used

Why: everything after this depends on the answer, and the answer is not guessable from the console.

gcloud policy-intelligence query-activity \
  --activity-type=serviceAccountLastAuthentication \
  --project=<PROJECT_ID> --format=json

Actual result: five accounts, three in use, two that had never authenticated — both default Compute Engine service accounts, holding no role anywhere.

Google Cloud service accounts list for the logging project, showing the default Compute Engine service account enabled.
The starting state, which cannot be recaptured: the default service account present and enabled, before anything was changed. The project number in the address is masked by the capture tooling.

Step 2 — Disable them, reversibly

Why: Google's guidance is to disable first and confirm nothing breaks. restore_policy = "REVERT" means a destroy puts the accounts back as they were, so the change can be undone in one field.

resource "google_project_default_service_accounts" "logging" {
  project        = var.logging_project_id
  action         = "DISABLE"
  restore_policy = "REVERT"
}

Step 3 — Close the key-creation constraint on the legacy generation

Why: the organization's baseline enforces iam.managed.disableServiceAccountKeyCreation. The legacy constraint of the same name had no policy at all, which evaluates to enforce: false — indistinguishable from the rule being off. Setting both is redundant while the baseline holds, which is what defence in depth means, and it removes a trap for whoever checks next.

HCP Terraform run showing Applied with three resources.
Validates deployment, and only deployment: three resources applied. Whether the right accounts were disabled is the next section.

Validation and Evidence

TestExpectedActualStatus
Infrastructure deployed3 resources3 added, 0 changed, 0 destroyedPass
Unused default accounts disableddisabled = True in both projectsboth disabledPass
Disabled, not deletedaccounts still resolveboth presentPass
Key creation blocked, both constraint generationsenforce: True on eachboth enforcedPass
No user-managed keys org-widezerozeroPass
Accounts left enabled are the ones in usereported, not asserted3 in use, 2 disabledPass
Nothing broke after the disableWeeks 06–08 validators still greenall still greenPass

Deploying is not the same as being right. Row one proves Terraform applied. Rows two to six prove the correct accounts were touched, and row seven proves nothing depended on them. The last row has no figure because its evidence is other validators' output, not a page.

The same service accounts list, now showing the default Compute Engine service account with status Disabled.
The result, paired with the before shot: the same view, same project, status now Disabled and the account still present. One picture of a disabled account would prove nothing; the pair proves a change.

Security and Cost

Security decisions

ControlDecision and trade-off
ReversibilityDisable rather than delete. The only irreversible step is avoided, because IAM's internal unique ID means a recreated account does not inherit the old bindings.
Evidence before actionNo account was touched on the basis of looking idle. "Never authenticated" is the only signal acted on.
Key creationBlocked on both constraint generations, so a later reader checking either name sees it enforced.
CredentialsNo service account keys. Zero user-managed keys exist org-wide, verified rather than assumed.
Accepted gapOnly two projects are in scope. Other projects in the organization still have enabled default service accounts.

For production, the usage query would run on a schedule across every project rather than once by hand, with a documented interval between disabling and deleting, and alerting on re-enablement.

Cost

$0. Disabling an identity costs nothing, Activity Analyzer queries are free, and nothing in this lab runs. Measured from the billing export rather than estimated.

Troubleshooting and Lessons

A security rule that appeared to be switched off

Problem: gcloud org-policies describe iam.disableServiceAccountKeyCreation --effective returned enforce: false — reading as "this lab's first rule is not enforced".

Root cause: constraints exist in two generations. The managed one was enforced by Google's baseline all along; the legacy constraint had no policy at all, and absent evaluates exactly like disabled.

Resolution: query both names before concluding anything, then set the legacy one too.

Lesson: enforce: false can mean "not set on this generation" rather than "not enforced". Checking one name nearly produced a confident, wrong security alarm.

An account that looked dormant and was not

Problem: finops-reader appeared unused and was a candidate for disabling.

Root cause: the console does not show last-authentication data; absence of visible activity is not absence of use.

Resolution: Activity Analyzer showed it had authenticated five days earlier. It was left alone.

Lesson: measure, never reason about which accounts look idle. This is the difference between an audit and a guess.

Cleanup and Key Takeaways

Cleanup

This week is deliberately exempt from teardown. Disabling an unused identity is the desired end state, not a demonstration, and it costs nothing to leave in place.

There is a catch worth knowing if you do destroy it: restore_policy = "REVERT" returns the accounts to their prior state, so a destroy re-enables them. That is the right default for a lab and the wrong one for a real cleanup — to keep them disabled, remove the resource from state rather than destroying it. Commands are in the lab guide.

Key takeaways

  1. A constraint reading false may simply not be set on that generation. Check both the legacy and managed names before concluding a rule is unenforced.
  2. Disable is reversible; delete is not — and the reason is IAM's internal unique ID, not the email address, which is the opposite of what most people assume.
  3. "Never authenticated" is the only safe signal. "Looks idle" is not a measurement, and one account here proved it.
  4. Default service accounts exist whether you use them or not. Every project gets one; the usual danger is an automatic Editor grant, which a baseline constraint can remove.

References

Comments

How was your experience?
Your feedback helps improve this site.
PoorExcellent