// Why this matters
Using Terraform preconditions to guard SaaS user and role access is a small idea with an outsized effect. Third-party SaaS access is typically granted in a web UI, where a mistyped address, a personal email or an over-broad role is a click away and leaves no review trail.
The engineering insight is that most access mistakes are not subtle policy errors; they are typos and category errors. A guard that says "this email is not on the company domain" or "this role is not in the allowed list" catches the majority before a human ever has to think about them.
Doing it at plan time matters. A check that runs after resources are created has already invited the wrong person. A check that blocks the plan means the wrong action cannot be reviewed, let alone approved.
// The problem
Database platform access has several dimensions: organisation-level roles, teams, per-project access for teams and sometimes direct per-project roles. Doing this by hand means each dimension can disagree with the others, and offboarding means visiting each.
Terraform helps with state but not with semantic validity. A variable of type map(string) happily accepts "Projct_Owner" or an address at a personal mail domain, and the provider only complains (if at all) when the API rejects it, often halfway through an apply after other invitations have been sent.
Finally, invitations are side-effecting and slow to undo: an invite email has been sent, a person has been notified, and cleaning up is a conversation, not a revert.
// The solution
Model access as data in three maps: users (email to org roles and team list), teams (team to project access level), and role bundles (a named set of org roles a user can inherit). Project access is expressed by team and level, with levels defined centrally as a map from a friendly name to the platform's role string.
Compute everything derived in locals: the effective roles per user (own plus bundle-derived, de-duplicated), the flattened list of (team, project, role) assignments and the set of all referenced names. The guard validates the referenced names against the defined ones.
The guard is a terraform_data resource with several preconditions, one per rule, each with a message that names the offending values. Every real resource has depends_on = [terraform_data.guard], so no provider call happens until the guard passes. I use preconditions, not check blocks, because a failing check is only a warning and the apply would proceed.
This is the same family of idea as the user-existence guard in One Config, Two Clouds: Group and Role Management as Code, applied to a SaaS provider with no directory behind it. Invitations require acceptance, which is documented rather than fought: Terraform manages the intent, and access takes effect when the person accepts.
- Edit access mapusers, teams, projects, levels in config
- Guard evaluation gatepreconditions on domain, role allow-list and references
- Abort or continuefailure stops the plan before any API call
- Teams createdthen invitations and team assignments
- Project accessteam and user grants resolved from levels
- Applythrough the normal pipeline
- Edit mapusers, teams, projects, levels
- Deriveeffective roles and flat assignments in locals
- Guard gatepreconditions on domain, roles, references, levels
- Abort or continuefailure stops the plan before any API call
- Teamscreated first
- Invitationsusers invited with effective org roles
- Team membershipusers attached to teams
- Project accessteam grants from levels
// Before you start
- Terraform 1.2+ for preconditions (1.4+ for
terraform_data) - The vendor provider and an API key with organisation owner rights, stored in your pipeline's secret store
- An agreed allow-list of roles and your company email domain
- Familiarity with locals, flatten and for_each
- A pipeline that plans on pull requests and applies on merge
// Step-by-step implementation
01 Define the access map and the allow-lists
Keep the data plain so non-Terraform readers can review it. Users list their org roles and teams; teams list their project levels; levels map friendly names to platform role strings. The allow-lists (domain, org roles) live in variables with defaults.
Prefer a map keyed by email over a list of objects: duplicates become an error at parse time, and the key is stable for state addresses.
02 Derive effective roles and flat assignments in locals
A user's effective roles are their own plus the roles of every bundle they inherit, de-duplicated and sorted. Sorting matters: set ordering is not stable across versions, and an unstable order produces spurious diffs.
Flatten team project access into a map with composite keys. Composite string keys survive insertions in the middle of the config, which index-based keys do not.
03 Write the guard resource with one precondition per rule
One rule per precondition, each with a message that includes the offending values. When a plan fails, the reviewer should know exactly what to fix without reading code.
Why
terraform_data? It is a built-in resource with no provider, so the guard cannot itself fail for provider reasons, and its lifecycle block is where preconditions live for a pure validation.04 Create teams and invitations behind the guard
Every real resource declares
depends_on = [terraform_data.guard]. Without it Terraform is free to start provider calls in parallel with the guard's evaluation, which defeats the point.Create teams first, then invitations with the effective roles. Invitations send mail, which is exactly why the guard exists.
05 Grant project access from team levels
Project access is assigned to teams, never to individuals. That keeps offboarding to one place: remove a user from a team and every project grant goes with them.
Resolve the level name to the platform role string through the central map, so a typo cannot reach the API. The project IDs come from a lookup keyed by friendly name.
06 Run it through the normal pipeline, with plan on every pull request
The guard only helps if the plan runs where reviewers see it. Plan on pull requests and print the plan, so a failing precondition appears as a red check with the message in the log.
Apply on merge from a protected environment. The API key lives in the environment secret store, and is the only credential the stack uses.
// How to verify it works
- Add a user with a personal-domain email and run
terraform plan: it must fail on the guard with that address in the message and no resources in the plan. - Give a user a role not on the allow-list: the plan must fail naming the role.
- Reference a team that is not defined: the plan must fail naming the team.
- Fix the data and plan again: the plan should show invitations, teams and project grants only.
- Run
terraform planon an unchanged main: it must report no changes.
// Design decisions and trade-offs
- Preconditions rather than check blocks, so failure blocks the plan.
- Effective roles are own plus group-derived, de-duplicated.
- Invitations require acceptance before access takes effect.
// Pitfalls and lessons learned
- A
checkblock only warns. For a control you need the plan to fail, use a precondition on a resource everything depends on. - If a real resource lacks
depends_onthe guard, Terraform may evaluate it first and send an invitation before the failure surfaces. - Sets have no stable order; sort derived lists or you will see phantom diffs on effective roles.
- Invitations are not access until accepted. People will report that "Terraform did nothing"; document that clearly.
- Project IDs in config are easy to mistype. Resolve them through a lookup map so an unknown name fails the guard.
- Removing a user from config cancels a pending invitation or removes membership; make sure reviewers read removals as carefully as additions.
// Frequently asked questions
What is the difference between a Terraform precondition and a check block?
A failed precondition stops the plan and apply; a failed check block only emits a warning. Use preconditions for controls that must block.
Where do I put validations that span several variables?
In a terraform_data guard resource with preconditions that reference locals, since variable validation blocks can only reference their own variable (before Terraform 1.9).
How do I stop external email addresses in Terraform-managed SaaS access?
Compute the list of addresses that do not end in your domain and assert it is empty in a precondition.
Can I manage MongoDB Atlas users and teams with Terraform?
Yes. The provider covers organisation invitations, teams and project-team access, which this pattern wraps with guards.
Why assign access to teams instead of users?
Offboarding and changes become single edits and reviewers read grants as role-to-team, not person-to-project.
// The outcome
Invalid access can no longer be planned, let alone applied.
// Where to take it next
- Apply the same guard pattern to other SaaS providers in your estate.
- Add an owner and expiry per user and fail the plan on expired entries.
- Combine with One Config, Two Clouds: Group and Role Management as Code so the same directory group drives SaaS membership.
- Review policy-as-data options in Guardrails and Engineering Telemetry: Org Policy, Project Factory, Gatekeeper, Four Keys.