Granting third-party auditors access to cloud infrastructure before a production cutover is one of the easiest ways to introduce lingering over-privileged identities. A quick click-ops assignment of a basic role (roles/viewer) or even a service-specific predefined role often grants far more visibility than the audit actually requires—and leaves no version-controlled trail behind.
In this write-up, I walk through how I replaced broad predefined GCP IAM access with a declarative, least-privilege Custom IAM Role provisioned in Terraform and verified via Cloud Asset Inventory (Policy Analyzer).
TL;DR
- What I built: A reusable Terraform configuration that creates a production-grade (
GA) GCP Custom IAM Role (Audit Team Reviewer) scoped to exactly two permissions and binds it non-authoritatively to an external audit principal. - Core security control: Decomposing
roles/firebasedatabase.viewerdown to two control-plane listing permissions (firebase.clients.listandfirebasedatabase.instances.list) usinggoogle_project_iam_memberto avoid IAM policy lockouts. - Key takeaway: Managing GCP IAM safely in Terraform isn't just about picking the right permissions—it requires understanding ETag concurrency, authoritative vs. non-authoritative bindings, and GCP's custom role soft-delete behavior.
adrianjadev / gcp-iam-custom-role-audit
Least-privilege GCP IAM engineering with Terraform-creating, binding, and auditing custom IAM roles to eliminate overly permissive access.
Least-Privilege Custom IAM Role for Third-Party Database Audits (GCP + Terraform)
Origin & Scenario: Declarative Infrastructure-as-Code (IaC) implementation of the Google Cloud Cybersecurity lab "Create a role in Google Cloud IAM" (Cymbal Bank cloud migration scenario).
Overview
During Cymbal Bank's cloud migration, a database storing sensitive customer billing and invoice data requires a third-party security audit before production deployment. Rather than assigning broad basic roles (Viewer, Editor, Owner) or over-scoped predefined roles, this repository provisions a least-privilege Custom IAM Role (Audit Team Reviewer) in Google Cloud using Terraform, binds it non-authoritatively to an audit principal, and verifies effective permissions using Cloud Asset Inventory / Policy Analyzer.
Architecture & Workflow
1. IAM Access Control Model
In Google Cloud, permissions are never attached directly to identities. Instead, granular permissions are bundled into a Custom Role, and a project-level IAM Policy Binding associates a…
👉 Full repository: github.com/adrianjadev/gcp-iam-custom-role-audit
1. The Problem: Why This Matters in Production
Consider a common pre-production cloud migration scenario: a financial services platform is preparing to launch a database storing sensitive customer billing and invoice data, and an external security team needs read-only inventory access to review the Firebase Realtime Database deployment before go-live.
In practice, teams frequently run into three security risks when provisioning this access:
- Over-scoped roles: Assigning project-wide basic roles (
Viewer,Editor,Owner)—or even the fullFirebase Realtime Database Viewerpredefined role—violates least privilege and expands the blast radius if an auditor's credentials are compromised. - Dangerous Terraform IAM mutations: Using authoritative Terraform IAM resources (
google_project_iam_policyorgoogle_project_iam_binding) can silently wipe out unrelated human or service-account permissions on the project, causing accidental lockouts or production outages. - Orphaned static access: Manually attaching permissions to an individual email address in the Cloud Console creates drift and makes it easy to forget to revoke access once the audit engagement ends.
Engineering objective: Provision the minimum required permissions declaratively in Terraform, bind them safely without disturbing existing project IAM policies, and verify effective permissions programmatically through Cloud Asset Inventory.
2. Architecture & Design
In Google Cloud IAM, permissions are never attached directly to identities. Instead, individual <service>.<resource>.<verb> permissions are grouped into a Role, and a project-level IAM Policy Binding connects a Principal to that role.
![GCP IAM Access Control Model]
When terraform apply runs, Terraform orchestrates two distinct GCP APIs before verification occurs in Cloud Asset Inventory:
- Cloud IAM API (
iam.googleapis.com): Validates the requested permissions and creates the project-scoped custom role (projects/{project_id}/roles/CustomRole) with launch stageGA. - Cloud Resource Manager API (
cloudresourcemanager.googleapis.com): Updates the project's single IAM allow-policy document using an optimistic-concurrency get-modify-set operation backed by the policy'setag. - Cloud Asset Inventory (
cloudasset.googleapis.com): Policy Analyzer evaluates effective permissions across the resource hierarchy—resolving custom role definitions rather than just inspecting raw JSON bindings.
![Provisioning and Verification Lifecycle]
Component Breakdown
| Component | Cloud Service / Tool | Security Purpose |
|---|---|---|
Custom IAM Role (Audit Team Reviewer) | GCP Cloud IAM (google_project_iam_custom_role) | Restricts access exclusively to firebase.clients.list and firebasedatabase.instances.list (implicit deny on everything else). |
| Project IAM Binding | Cloud Resource Manager (google_project_iam_member) | Non-authoritatively binds the audit principal to the custom role without overwriting existing project IAM bindings. |
Input Isolation (terraform.tfvars) | Terraform (>= 1.5.0) | Decouples environment-specific project_id and auditor_member values from reusable HCL code (and keeps .tfvars out of Git). |
| Effective Access Audit | Cloud Asset Inventory / Policy Analyzer | Independently verifies which principals hold effective access to target database resources across the hierarchy. |
3. Security Controls & Implementation Deep Dive
Control 1: Decomposing Predefined Roles into a GA Custom Role
Instead of assigning the entire roles/firebasedatabase.viewer predefined role, the custom role strips access down to two specific control-plane inventory permissions. Because GCP IAM operates on default-deny, any action outside this explicit list is automatically rejected.
Setting stage = "GA" (General Availability) explicitly marks the role as production-ready and stable rather than experimental (ALPHA) or evolving (BETA).
resource "google_project_iam_custom_role" "audit_team_reviewer" { project = var.project_id role_id = "CustomRole" title = "Audit Team Reviewer" description = "Least-privilege role for third-party Firebase Realtime Database inventory audits" stage = "GA" permissions = [ "firebase.clients.list", "firebasedatabase.instances.list", ] } Control 2: Non-Authoritative Bindings (google_project_iam_member) & ETag Concurrency
Choosing the right Terraform IAM resource is a critical safety decision in GCP:
-
google_project_iam_policyis authoritative for the entire project—it replaces every IAM binding on the project (high lockout risk). -
google_project_iam_bindingis authoritative per role—it removes any principal on that role not declared in the resource block. -
google_project_iam_memberis non-authoritative (additive)—it performs a read-modify-write update using the policy'setagand safely manages a single(role, member)tuple.
resource "google_project_iam_member" "auditor_binding" { project = var.project_id role = google_project_iam_custom_role.audit_team_reviewer.id member = var.auditor_member # Optional IAM Condition pattern for time-bound third-party audits: # condition { # title = "Audit Window Expiration" # description = "Automatically expires third-party audit access after the review window" # expression = "request.time < timestamp(\"2027-01-31T23:59:59Z\")" # } } Control 3: Parameterizing for Group Principals & Ephemeral Access
Binding IAM roles directly to individual user emails creates operational drag and stale access when personnel rotate. By externalizing auditor_member into terraform.tfvars (copied from terraform.tfvars.example), the module supports both individual principals for testing and Google Groups (group:external-auditors@example.com) for clean lifecycle management—and pairs naturally with time-bound IAM Conditions (request.time < timestamp(...)) so access self-expires after the audit window.
project_id = "your-gcp-project-id" auditor_member = "user:auditor@example.com" # Prefer "group:..." in production Verification & Testing
Before applying, ensure the target project has iam.googleapis.com, cloudresourcemanager.googleapis.com, and cloudasset.googleapis.com enabled, and that the deploying identity holds roles/iam.roleAdmin and roles/resourcemanager.projectIamAdmin.
- Provision the custom role and binding:
cp terraform.tfvars.example terraform.tfvars terraform init terraform plan terraform apply - Verify effective permissions with Cloud Asset Inventory (Policy Analyzer):
gcloud asset analyze-iam-policy \ --project="your-gcp-project-id" \ --identity="user:auditor@example.com" \ --expand-resources Policy Analyzer resolves the custom role definition against the resource hierarchy, confirming that Audit Team Reviewer grants only the two expected listing permissions and nothing broader.
4. Lessons Learned & Production Hardening
Key Engineering Takeaways
- The Custom Role Soft-Delete Gotcha (
409 Already Exists): Runningterraform destroydoes not immediately free a custom role'srole_id. GCP places deleted custom roles into a pending-deletion (soft-delete) window. Re-runningterraform applyright away with the samerole_id(CustomRole) triggers a409 Already Existsconflict. In ephemeral test environments, either append a randomized suffix torole_idor restore the role first with:
gcloud iam roles undelete CustomRole --project="<PROJECT_ID>" - Control-Plane vs. Data-Plane Scope:
firebase.clients.listandfirebasedatabase.instances.listgrant control-plane metadata visibility (listing Firebase clients and RTDB instances), not arbitrary data-plane reads of database records (which are additionally governed by Firebase Security Rules and data-plane permissions). Clarifying whether auditors need configuration/inventory visibility vs. record-level data access prevents mid-audit friction. - IAM Eventual Consistency: Newly created custom roles and policy bindings propagate asynchronously across GCP's distributed IAM caches—sometimes taking seconds to a couple of minutes. Automated post-apply checks should always account for transient
403responses with retry/backoff logic. - Least Privilege Applies to Terraform Too: Using
google_project_iam_memberinstead of authoritative policy blocks eliminates an entire class of self-inflicted IAM outages when multiple teams share a GCP project.
Taking This Further in Production
This repository focuses on cleanly modeling the custom role, binding, and verification workflow. To harden this pattern for an enterprise production environment, the next steps I would implement are:
- Remote State with Locking: Store Terraform state in a versioned, CMEK-encrypted Cloud Storage (GCS) backend instead of local state files so IAM changes are auditable and concurrency-safe across teams.
- Keyless DevSecOps CI/CD Pipeline: Run
terraform fmt -check,terraform validate, Checkov/Trivy IaC misconfiguration scans, and Gitleaks secret scanning in GitHub Actions—authenticating to GCP via Workload Identity Federation (OIDC) with zero long-lived JSON service account keys. - Organization-Level Custom Roles & Audit Alerting: Promote standardized audit roles to the GCP Organization level for reuse across projects, and route Cloud Audit Logs (
SetIamPolicy,CreateRole,UpdateRole) to a SIEM or alerting sink to detect unexpected IAM drift or privilege escalation.
Explore the Code
You can inspect the full Terraform configuration (main.tf, variables.tf, outputs.tf, versions.tf), prerequisites, and cleanup notes in the repository:
- Repository: github.com/adrianjadev/gcp-iam-custom-role-audit
- More GCP & Cloud Security IaC Projects: github.com/adrianjadev
How does your team handle temporary third-party audit access in GCP—custom roles with IAM Conditions, or Privileged Access Manager (PAM)? I'd love to hear your patterns in the comments.

