Identity & Access · Group creation

One Config, Two Clouds: Group and Role Management as Code

A single Terraform stack defines every security group, its members and its role assignments for both Entra ID and Google Workspace/GCP, and keeps them reconciled.

  • Terraform
  • azuread / azurerm
  • googleworkspace / google
  • Cloud Identity API
  • Microsoft Graph
  • SCIM
  • GitHub Actions

// Why this matters

Managing Entra ID and Google Cloud groups with Terraform from one config sounds like a convenience, but it is really a control problem. Access is the thing auditors, security teams and new joiners all ask about, and when it lives in two consoles and a handful of small stacks the honest answer to "who can do what, and why" is "go and look".

The engineering motivation is consistency. A person who joins a team needs the same logical access on Azure and on GCP, and a person who leaves needs it removed from both on the same day. If each cloud has its own process, the two drift apart within weeks, and the drift is invisible until someone gets an audit finding.

Putting the whole thing in one reviewed config gives you a single change path (a pull request), a single history (git blame is your audit log) and a single place to enforce rules such as "no external addresses" or "every group has an owner".

// The problem

Before this, access was granted per cloud, partly by hand and partly through many small stacks. Each stack owned a slice of groups, nobody owned the whole picture, and the Azure and GCP sides were edited by different people at different times. Onboarding meant two tickets; offboarding meant remembering both.

There are also hard technical traps. A group can only be granted a role if the user already exists, but Terraform discovers a missing user at apply time with an error that names a nested resource, not the typo. Google does not natively read your Entra directory, so membership has to travel through provisioning. And the moment the config reaches a hundred groups, plans slow down because every role binding drags a list call to a cloud API with it.

Finally there is state hygiene. A config that grows organically gets refactored: groups move between modules, keys get renamed. Without a plan for that, every refactor is a destroy-and-recreate of a security group, which is exactly the thing you cannot do casually to something other systems reference by ID.

// The solution

The design is a single root module driven by one large variable: a map keyed by group name. Each value carries the group identity, its members, and lists of role grants per scope. On the Azure side the scopes are management group, subscription, resource group and individual resource. On the Google side they are organisation, folder, project and billing account. The same logical group can appear on both sides with the same member list.

Reconciliation between the clouds is deliberately indirect. Entra ID is the source of truth for people. Terraform adds Azure users to a dedicated sync group, a SCIM provisioning job pushes them into Google, and only after the job has run and the users are visible does the Google half of the stack add them to Cloud Identity groups. Trying to create Google users directly would have created a second identity system; riding the existing provisioning keeps one.

Safety lives at plan time. A validation resource with lifecycle preconditions looks up every referenced user in both directories and fails the plan with a readable message if one is missing. Service accounts are excluded from that check because they are not directory users. Every group and role resource depends on the validation resource, so nothing can be planned past it.

I considered one stack per cloud and one stack per team. Per-cloud stacks make the two sides drift again; per-team stacks make cross-cutting rules impossible to enforce. The cost of one big stack is plan time and blast radius, which we handle with cached hierarchy snapshots, ordered applies and a strict review gate (see Making a 2,000-Member Identity Plan Fast, Safe and Authoritative for the performance half and The App Registration Factory That Cannot Hold a Secret for the automation identity it runs as).

How it flows flow1. Config change → 2. Lint and scan → 3. Existence validation → 4. Plan → 5. Gate: changes → 6. Approval → 7. Azure groups and RBAC → 8. Sync to Google → 9. Google groups and IAM → 10. Notify01Config change02Lint and scan03 · GATEExistence validation04Plan05 · GATEGate: changes06Approval07Azure groups and RBAC08Sync to Google09Google groups and IAM10Notify
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Config changea pull request edits the declarative group, member and role config
  2. Lint and scanfmt, validate, TFLint and Checkov
  3. Existence validation gateplan fails early if a referenced user is missing in either directory
  4. Plandetailed exit code decides whether anything changed
  5. Gate: changes gateno changes skips apply; a plan error stops the run
  6. Approvalapply job runs in a protected environment
  7. Azure groups and RBACgroups, role assignments, eligible (PIM) assignments
  8. Sync to Googleadd to sync group, trigger SCIM, wait, verify
  9. Google groups and IAMcreate groups, then org, folder, project and billing roles
  10. Notifyoptional chat message with a plan summary
Declarative configgroups mapmembersrole grants per scopestrict + create flagsValidationuser lookupsservice-account filterpreconditionsAzureEntra groupsRBAC assignmentsPIM eligible rolesSCIM sync groupGoogleCloud Identity groupsorg / folder IAMproject IAMbilling IAM
Where each concern lives. One config feeds two provider stacks; people flow Azure to Google through SCIM, not through Terraform.
ReviewerPipelineEntra IDSCIM jobGoogleMerge config changeValidate user existsAdd to group and sync groupTrigger on-demand provisioningCreate or update userVerify user, then add to Cloud Identity group
Adding one person to one group. The order matters: Google membership is only attempted after the SCIM job has made the user visible.

// Before you start

  • Terraform 1.5 or newer (preconditions need 1.2, moved blocks need 1.1, removed blocks 1.7)
  • An Entra ID tenant and a service principal allowed to manage groups and read users (Group.ReadWrite.All and User.Read.All, or narrower ownership based permissions)
  • Azure RBAC rights to create role assignments at the scopes you will use (User Access Administrator or a custom role with roleAssignments/write)
  • A Google Workspace or Cloud Identity tenant, the Cloud Identity API enabled in a billing-enabled project, and a service account with group admin rights via domain-wide delegation or the groups admin role
  • An Azure-to-Google SCIM provisioning app already configured to sync one named group
  • Familiarity with Terraform for_each, locals and variable validation

// Step-by-step implementation

  1. 01 Model every group as data

    Start with the config shape, because everything else is a projection of it. One map, keyed by a stable group name, with optional lists per scope. Stable keys matter: the key is part of every resource address, so renaming it is a state operation.

    Keep role grants as plain strings so a reviewer can read a diff without knowing Terraform. Use the same key for the Azure and Google side of a logical group; a cloud list on the group says which halves exist.

  2. 02 Validate users at plan time with preconditions

    Look up every member through a data source that tolerates absence, then assert on the result in a lifecycle precondition. The trick is to use azuread_users with ignore_missing = true, which returns what it found rather than failing, so you can compute the difference and print it.

    Put the assertion on a terraform_data resource and make every real resource depend on it. A check block would only warn; a precondition on a resource that everything depends on stops the plan before any write API is called.

  3. 03 Create Entra groups and RBAC at four scopes

    Flatten the nested role maps into a single list of objects, then turn it into a map with a deterministic key. Deterministic keys are what make later plans quiet: if a key depends on list position, inserting a line in the middle rewrites every assignment after it.

    Strict membership is handled by the group resource itself. Setting members on azuread_group makes the list authoritative and removes anyone not listed; for groups you only borrow, set create = false and use a membership resource per member instead, so you never remove people you do not own.

  4. 04 Push users to Google through a SCIM sync group

    Do not create Google users in Terraform. Add the Azure users to the group that the provisioning app is scoped to, then trigger an on-demand provisioning job so you do not wait for the next 40 minute cycle. The trigger is a Graph call; wrap it in a terraform_data with a local-exec so it runs after the membership changes.

    Then wait and verify. Poll the Google side until every expected user resolves, with a bounded retry. If you skip the wait, the Google group membership resource fails with a not-found error that looks like a bug and is only a race.

  5. 05 Create Google groups and bind IAM at every level

    The Google half mirrors the Azure half. Create the group with the Cloud Identity groups resource, add members, then bind roles. Build the binding maps the same way: a flat map with deterministic keys, one binding per (scope, role).

    Use authoritative bindings only where you truly own the role at that scope. Additive iam_member style bindings are safer for shared projects; authoritative ones are right when the config is the only writer. I expose that as a mode switch and default to additive.

  6. 06 Cache the resource hierarchy to dodge API rate limits

    Resolving folder and project names to IDs at plan time means listing the whole organisation tree on every run. At scale that hits quota. Snapshot the hierarchy into a JSON file, commit it, refresh it from a scheduled job, and read it with jsondecode(file(...)).

    The config then refers to friendly names, and the lookup is a local map read. The snapshot job is a ten line script; the important property is that it only ever writes the JSON file, never state.

  7. 07 Survive refactors with moved blocks, and add the pipeline

    When you rename a map key or move a resource into a module, declare it in a moved block instead of editing state by hand. The block is reviewed in the same pull request as the rename, and Terraform shows it as a move in the plan, not as a destroy and create. Keep them in a dedicated file; ours grew large and that was fine.

    The pipeline is the same shape as any Terraform pipeline with three additions: validation runs first, the plan uses -detailed-exitcode so "no changes" skips apply, and the apply job sits behind a protected environment. Foundation layers (service accounts, the automation identity) are applied in a separate, documented order before this stack.

// How to verify it works

  • Add a deliberately misspelled user and run terraform plan: it must stop in the guard resource with the misspelling listed, and no provider API write must appear in the logs.
  • Run terraform plan on an unchanged main: the detailed exit code must be 0 and the apply job must be skipped.
  • Add a new test user: after apply, az ad group member list --group platform-sre shows them and the Google side shows the same address in the Cloud Identity group within a SCIM cycle.
  • Remove a user from the config with strict membership on: the next plan must show exactly one removal in each cloud.
  • Rename a group key with a moved block: the plan must show moves only, no destroys.

// Design decisions and trade-offs

  • Preconditions validate users at plan time to avoid cryptic apply-time errors; service accounts are excluded from user validation.
  • A strict-membership option removes unauthorised members automatically.
  • A create=false flag lets the stack manage permissions on pre-existing, imported groups.
  • Cached JSON snapshots of the resource hierarchies avoid API rate limits; a large moved-block file preserves state through refactors.
  • Honest gap, documented: monitoring for this stack was designed but still commented out.

// Pitfalls and lessons learned

  • Renaming a map key without a moved block destroys and recreates the group, which breaks every external reference by object ID. Review state moves as carefully as access changes.
  • SCIM is eventually consistent. Without the wait-and-verify step, the Google membership apply fails intermittently and people blame Terraform.
  • Authoritative IAM bindings at organisation or folder scope will quietly remove bindings someone added in the console. Default to additive and opt in per scope.
  • Preconditions only run when the resource is in the plan. If the guard resource is not a dependency of everything, a typo can slip past it.
  • Group creation and role assignment in a single apply can race on directory replication; a short retry or a second apply fixes it, but it looks like a permissions error first.
  • Service accounts look like users in a member list. Filter them out of user validation or every plan fails.
  • A very large config makes the plan slow; see Making a 2,000-Member Identity Plan Fast, Safe and Authoritative before it becomes a problem.

// Frequently asked questions

How do I manage Entra ID groups with Terraform?

Use the azuread provider: azuread_group for the group, azuread_group_member or the members argument for membership, and azurerm_role_assignment for RBAC. Drive them from a single map with for_each so every group is data.

Can Terraform create Google users from Entra ID?

Not sensibly. Use SCIM provisioning for users and let Terraform only manage group membership and IAM, after the users appear.

Authoritative or additive IAM bindings?

Additive when other writers exist on the same scope; authoritative only where the config is the sole owner of that role. Mixing them on one role is how bindings disappear.

How do I refactor Terraform without recreating groups?

Use moved blocks (Terraform 1.1+) in the same pull request as the rename, and confirm the plan shows moves rather than replacements.

Why validate users in a precondition?

It turns a cryptic apply-time provider error into a plan-time message naming the exact typo, and it prevents a half-applied change.

// The outcome

One reviewed change path for 100+ groups across two clouds from a config of 1,500+ lines.

// Where to take it next

  • Add a scheduled plan-only run for drift detection, as described in Making a 2,000-Member Identity Plan Fast, Safe and Authoritative.
  • Add owner and expiry fields to the group schema and enforce them with validation blocks.
  • Wire plan summaries into chat so reviewers see the human-readable diff.
  • Extend the same pattern to just-in-time eligible role assignments.

// Keep reading