Conditional Access · Identity as code

Conditional Access that stays the way it was designed

A 44-policy zero trust baseline for AU/NZ small and mid-market organisations of 200+ employees with a multi-admin operating team, designed to be operated on an ongoing basis by an MSP acting as an extension of each customer's internal IT function. One model generates the Terraform, one apply builds every object in the tenant, and a verification pass diffs the live tenant against the design afterwards, so a hand edit in the portal gets caught and reverted instead of quietly becoming the new normal.

44 policies · 12 persona groups · 4 named locations Terraform + Microsoft Graph Zero trust, no location-based MFA exemptions Validated in a live Entra tenant
Watch the walkthrough
1
Terraform apply builds all 60 objects in a tenant, identically every time
0
drift tolerated. A portal edit is reverted by the next apply
27
privileged roles defined once, and a lint rule fails the build if any policy disagrees
3
full destroy and apply cycles before a build is signed off

Built from running Conditional Access across dozens of Microsoft 365 tenants, and redesigned for the scale where managing it in the portal stops being safe. The policy design starts from an established, well-known industry Conditional Access framework, rebuilt around a persona-based group taxonomy and a portable named-location architecture, then hardened throughout to one standard: every access decision is anchored to identity assurance, device compliance or assessed risk.

MASTER BASELINE changed once, then copied into every tenant Source policy JSON the single model Model compiler emits the Terraform and the expected matrix together Lint + coverage checks fail the build if a design rule or a source value breaks resolved by must pass versioned build, copied into each tenant's folder hand edit in portal reverted on next apply EVERY TENANT own folder, own state Tenant folder Terraform config + expected matrix terraform.tfvars · this tenant's values terraform.tfstate · what it created Entra ID tenant 44 Conditional Access policies 12 persona groups · 4 locations 60 objects, all deployed off terraform plan, then apply as a short-lived app registration Drift check 60 of 60 match, or it isn't finished expected state reads via Graph
One model drives everything. The generator emits the Terraform and the expected-deployment matrix in the same run, so what gets deployed and what gets checked can't disagree. Every tenant has its own folder and state, the apply runs as a deployment identity that's deleted at the end of the engagement, and verification reads the tenant back rather than trusting that the apply worked.
◆ The decision everything else follows from

The tenant is not the source of truth. The code is.

Every design choice below comes out of that one commitment. Policies are generated from a model, applied by Terraform, and verified by diffing the live tenant against what the model said should be there. A policy edited by hand in the portal gets reverted on the next apply, without discussion.

✓ 60 objects per tenant, identical every time: 44 policies, 12 groups, 4 named locations.
✓ Everything deploys disabled. A policy that's off can be reviewed. A policy that was skipped is invisible.
✓ Verification is a diff, generated from the same model the policies came from.

Where it stands. The twelve-policy set this grew out of runs in production across dozens of tenants. This redesign has been through a live Entra tenant, including the licensing failures in section 09, and isn't yet running in a business.

01

Why Terraform, and not a PowerShell script

Almost every Conditional Access automation I've seen is PowerShell against Microsoft Graph. It's the obvious choice, the examples are everywhere, and for a one-off build it's completely fine. It stopped being fine the moment I started thinking about dozens of tenants and an eventual exit from each one.

Here's the thing a script can't do. It creates objects and then forgets them. Ask it what it made in a tenant eight months ago and it has no answer, because there's nothing holding that knowledge except the tenant itself and whatever notes somebody kept.

That matters most at the end of an engagement rather than the start. When a customer leaves, you need to remove what you put in and nothing else. With a script you're hand-writing a teardown against a list you hope is accurate, in a tenant that's had eight months of other people's changes in it. With Terraform, state knows exactly which objects it created, and destroy removes those and leaves everything else alone. Clean exit, no archaeology.

A PowerShell script
Terraform
Creates objects and forgets them. What it made lives only in the tenant.
State records every object it created, so the code can answer questions about the tenant.
Teardown is hand-written against a list you hope is right.
destroy removes exactly what it created and nothing else. That's the clean-exit story.
Run it and find out what changed.
plan shows the diff before anything lands. You approve what you reviewed.
Run it twice and you get duplicates, unless you wrote the guard logic yourself.
Idempotent as a property of the tool, not something re-implemented per script.
Drift detection means writing a second script.
plan against an unchanged tenant is the drift report. No changes, or it names what moved.

The plan step deserves its own mention, because it changes the risk profile of touching identity controls at all. Conditional Access is the one place where a bad change locks everybody out of everything, including you. Being able to read exactly what will happen, before it happens, against a real tenant, is worth the entire learning curve on its own.

There's a transferability argument too. Terraform is what the rest of the infrastructure world already uses, so the baseline stops being a special snowflake maintained by whoever wrote the scripts. Anyone who's managed infrastructure as code can read it.

What Terraform doesn't solve

Provider coverage isn't complete. Terms of Use agreements have no Terraform resource at all, so that one object gets created in the portal and its ID passed in as a variable. There will be more of these, and pretending otherwise would be daft.

It also adds a thing to secure. Every tenant now has a state file containing the full object graph, and state security becomes its own piece of design work rather than an afterthought.

And the audience matters. The engineers who'd deploy this know Entra, Intune and Graph PowerShell cold. Terraform isn't assumed, so the runbook is written for someone who's never run it, and the commands are the same every time.

02

Four things that break on the way up

A twelve-policy set for a thirty-person business is the right amount of machinery. It doesn't survive being scaled, and the reasons are more interesting than "you need more policies."

Exclusions

They stop being a handful of named accounts

In a small tenant you carry the exclusions in your head. Add a service account that can't do MFA, a meeting room, some legacy-auth devices, a directory sync identity, and per-policy exclusion groups multiply until nobody can answer "who bypasses this control" without opening twelve policies and cross-referencing. That's what forced the move to persona groups: twelve groups mapping to kinds of identity, referenced by every policy that needs to treat that kind differently.

Group membership

It becomes an attack path

With two administrators, the person who can edit a group is the person who wrote the policy. With five or six holding various roles, an exclusion group that anyone with Groups Administrator can edit is a Conditional Access bypass with a friendly interface. So every group used as an exclusion is role-assignable, and only a Privileged Role Administrator can change who's in it. One dynamic group structurally can't be, and that exposure is written down rather than glossed over.

Role-assignable stops the wrong person changing membership. It doesn't stop the right person forgetting. So in production every exclusion group is also alerted on, with a threshold that fits what the group is for. A user pulled out of device compliance while the service desk troubleshoots gets 24 hours. After that, security is sent a ticket to work through with the service desk why the exclusion is still in place. Temporary exclusions that nobody chases are how a baseline erodes, one convenience at a time.

Location

It starts getting used as a shortcut

The temptation in a smaller tenant is to let the office IP range reduce friction somewhere. Registering a new MFA method from the office, say. If zero trust is the actual goal rather than the label, that has to go: no policy in this design grants access, reduces authentication friction, or exempts anyone from MFA on network position alone. Trusted location is a restriction layered on top of identity controls, never a relaxation of them. New starters bootstrap through a Temporary Access Pass instead, which is time-boxed and anchored to an identity rather than to where somebody happens to be sitting.

Definitions

"Admin" drifts

Twelve policies with one or two admin-facing, and you'll spot a role list that disagrees. With 44 policies and a dozen admin-facing, it drifts silently, because nobody reads 44 policies hunting for a role that's present in twelve of them and missing from the thirteenth. The canonical set of 27 privileged roles is emitted once and referenced everywhere, and a lint rule fails the build if that stops being true.

03

The 4pm Friday problem

This one I do see, and most of the engineering is aimed at it.

Somebody makes a change to get a director back into their mailbox. It works. It never gets written down.

Months later that tenant has one fewer policy than the design says, or one with a quietly widened exclusion, and nobody can tell you which. Nobody did anything wrong. The portal accepts edits from anyone holding the role and holds no opinion about whether the edit matched the design. At twelve policies in a tenant you know well, you catch it. At 44 across a multi-admin team, you don't.

So the next apply reverts it. No change request, no debate about whether the edit was reasonable. The discomfort people feel about that is the right reaction to have and then get past, because the alternative isn't a tenant with no drift. It's a tenant where the drift is permanent, invisible, and belongs to somebody who left.

If a change is worth keeping it goes into the model and lands everywhere. If it isn't worth putting in the model, it wasn't worth making on a Friday afternoon either.

Changes flow strictly from the master baseline to customer tenants, never the other way. A change to the shared design is made once in the generator and regenerated. A change for one customer is a variable value in that customer's configuration, never an edit to a deployed policy. Releases are versioned by month and sequence, cut when they're ready rather than on a calendar.

04

Everything gets created, nothing gets enabled

Every policy deploys disabled, and the location objects deploy with placeholder content that matches nothing real until the tenant's values are supplied.

A policy that exists but is switched off can be reviewed, piloted in report-only, and promoted on a schedule. A policy skipped because an input was missing doesn't appear anywhere. Not in the portal, not in a report, not in anyone's head. The gap it leaves gets found by an attacker rather than an engineer.

The locations are the same argument from the other side. A policy that includes all locations and excludes trusted ones matches every sign-in in a tenant with no trusted locations defined. So the objects get created unconditionally, and it's their content that varies per tenant, not their existence.

05

Verification is a diff, not a walkthrough

After apply, a PowerShell script reads the live tenant through Graph and compares it against an expected-deployment matrix generated from the same model the policies came from.

PS> .\Invoke-DriftCheck.ps1 -TenantId <redacted> Reading live tenant via Microsoft Graph... Comparing against expected-deployment matrix Security groups 12 / 12 MATCH Named locations 4 / 4 MATCH Conditional Access 44 / 44 MATCH 60 objects verified. No drift.

Everything matches, or the deployment isn't finished.

This replaced a checklist. Checklists are fine right up until somebody tired ticks a row they didn't actually check, and the failure mode of a checklist is silence. A diff either passes or it names the object that's wrong.

Proving idempotency instead of assuming it

Three full destroy and apply cycles before I'd call a build done, and re-running apply against an unchanged tenant has to report nothing.

$ terraform apply No changes. Your infrastructure matches the configuration.

There's a lot of infrastructure code out there that's only ever been run forwards. It works the first time and breaks quietly on the second, and you find out during an incident rather than during a build.

06

Eight rules every policy obeys

These are the design. Every group, location and exception path comes out of one of them, and the lint step exists to make sure none of them quietly stops being true.

  1. Device trust means Intune compliance, nothing else. Hybrid join appears nowhere as a grant. A domain join asserts a join state, not a patch level or a working EDR agent.
  2. Device policies cover every app, every platform, browser and client. Scoping to Office 365 alone leaves SSO-connected SaaS open to a stolen session cookie after an adversary-in-the-middle phish. Unknown platforms are blocked, because the user agent is attacker-controlled.
  3. Registering an MFA method always needs MFA, from anywhere. New starters bootstrap with a Temporary Access Pass, not with their position on the office network.
  4. Every unavoidable exemption carries a compensating control. Meeting rooms and legacy devices can't do MFA, so they're confined to trusted egress IPs. An exemption with nothing behind it is a hole.
  5. "Admin" is defined once. One list of privileged roles, referenced everywhere, enforced by lint.
  6. Temporary exceptions never touch admin policies. A user with a misreporting device gets relief on user-level device policies. An admin with the same problem uses another device.
  7. Workload identities are targeted by group membership, not by a list of named principals baked into a policy.
  8. Everything is created, nothing is enabled. An off policy can be reviewed and promoted. A skipped one is invisible until an attacker finds the gap.

And the one-line version over all eight: no policy grants access, reduces friction, or exempts anyone from MFA on network location alone. Location only ever adds restriction.

At a glance

Component
Quantity
Conditional Access policies, default build
44, generated as Terraform from the source policy model
Optional policies
3, built or enabled per customer only when a specific need or licence exists
Persona groups
12, nine of them role-assignable
Named locations
4, created on every deployment
Objects per tenant
60, the same set every time
Authentication strengths
Microsoft built-ins only. No custom strengths in the master baseline

Trusted locations are reached through Microsoft's built-in AllTrusted keyword rather than by GUID, which is what makes the location-aware policies portable across tenants without editing. AllTrusted is treated strictly as a location signal, never as an identity or device signal. It gates service accounts that can't do MFA, adds a restriction on admins rather than a relaxation, and keeps meeting rooms and legacy-auth devices to the sites they physically live at. It's never used to exempt anyone from MFA.

Category
What it's for
Prerequisite · 4
Close the shortcuts first: legacy auth, device code flow, authentication transfer. Enforced first, lowest user impact.
Device · 15
Compliance, platform and device state, per platform, with a separate admin device policy that takes no exceptions.
Location · 6
Country blocking and trusted-IP gates for the identities that can't do better: sync accounts, rooms, legacy devices, and admins as an extra layer.
User and risk · 19
MFA, phishing-resistant MFA, guests, sign-in and user risk, terms of use and admin session controls.

The policy set

Grouped by what each policy does. Open a category to see its policies.

Prerequisite 4 policies
PRE-01 to 04Close the shortcuts before anything else: legacy authentication, device code flow and authentication transfer. Enforced first, lowest user impact
Device 15 policies + 1 optional
DEV-11 to 13Compliant device required, one policy per platform. All cloud apps, browser and desktop clients
DEV-14, 15Compliant device required for users across all cloud apps
DEV-20Registering or joining a device requires MFA
DEV-30Admins: compliant device required. No partner or temporary exception, ever
DEV-40 OPTIONALApp-specific device requirement, built per customer
Location 6 policies + 1 optional
LOC-10Block every country outside the approved set. No device exemption; travel exception only
LOC-11Less-trusted countries allowed only from a compliant device
LOC-20Registering an MFA method requires MFA from anywhere. Travel never excluded
LOC-30Directory sync accounts only from trusted service-account egress
LOC-31Admins additionally restricted to trusted corporate locations
LOC-32Meeting rooms and legacy devices confined to trusted IPs, compensating for their MFA exemption
LOC-90 OPTIONALNamed restricted accounts limited to specific allowed locations
User and risk 19 policies + 1 optional
ID-10MFA for all users. Excludes exactly the admin role list, which is covered by stronger policies
ID-20Admins: phishing-resistant MFA. No guest exclusion, by design
ID-21Admins: additional sign-in control on the shared role list
ID-22Phishing-resistant MFA for everyone, once the registration runway has run
ID-23, 24Admin session controls on the shared role list
ID-30Security info registration, with Temporary Access Pass for new starters
ID-40 to 43Guest and external user controls, using the native guest selector so protection applies at first sign-in
ID-50, 51Sign-in and user risk responses (Entra ID P2)
ID-52, 53High-risk block, which applies to directory sync accounts too
ID-60, 61Session control through Defender for Cloud Apps
ID-70Terms of use acceptance
ID-90 OPTIONALWorkload identity risk (needs Workload ID Premium)

Identifiers on this page are for illustration and don't match the production naming.

07

Exceptions without holes

Every baseline needs ways around it. The design question is what each way around is never allowed to touch.

Groups are named by lifecycle rather than by purpose: break-glass, permanent technical exclusions, personas, and time-boxed exceptions. Nothing is called "Exclusion", because whether a group excludes or targets is a property of the policy, not the group. The lifecycle tells you what the membership should look like at any moment. Break-glass never changes. Permanent groups are small and stable. Temporary groups are empty most of the time, so verification reports their count on every run.

Travel

A location exception, and only a location exception

Travelling staff get relief from the country and location policies and nothing else. MFA, device compliance and MFA registration stay in force. There's deliberately no "compliant laptop can sign in from anywhere" shortcut, because each approved trip also raises a SOC advisory with destination and dates. That's how impossible-travel detection reads correctly, and it makes any unrecorded foreign sign-in anomalous by definition.

Partners

MSP engineers are the highest-value credentials in the tenant

A partner engineer can't enrol one laptop into every customer's Intune, so they're relieved of user-level device platform policies. They're never relieved of the admin device policy, any MFA policy or any location policy. The relief is the minimum the operating model needs, not the maximum it can bear.

Guests

Privileged guests stay outside the baseline

A guest can't enrol a FIDO2 key or Windows Hello in a tenant it doesn't own, so it can't meet the phishing-resistant MFA required of every admin. Rather than weaken that policy for everyone, privileged guest access is handled per engagement: time-bound, named, with compensating session controls and alerting on every sign-in.

Why derived lists need a reviewer

The blocked-countries list isn't maintained by hand. The build takes every country code and subtracts the approved and less-trusted countries, so adding a country to "less trusted" is an access-granting change. An early revision used a real country pair as placeholder values for the less-trusted list. Because of the subtraction, that would have quietly removed both from the block list, and one of them was North Korea. The placeholder is now a country with no people and no address space, and sanctioned countries are never allowed in the less-trusted list.

08

Three hours of engineering, three months of watching

The build is fast. Turning it on safely isn't, and shouldn't be.

PhaseGate to move onTypical
Scoping and licensingLicence baseline confirmed. Entra ID P2 is a hard gate1 to 2 weeks
Pre-build readinessGo / no-go checklist all yes1 to 3 weeks
Deploy identity and variablesPlan is clean and shows exactly what's expectedHalf a day
Apply and verify, all offEvery object matches. Break-glass sign-in tested and the alert fires1 day
Report-onlyNo unexplained impact7 to 14 days
Enforcement in wavesEach wave clears its own observation window6 to 12 weeks

Some policies are held back until their preconditions are real rather than assumed: location policies until the customer's actual egress IPs are verified against firewall config or sign-in logs, not an email; phishing-resistant MFA for everyone until the registration runway has run. Risk policies go live in the same wave as the location policies, so there's something watching for abuse of network trust from the moment it starts being used.

The groups are created empty, so they're populated straight after apply, break-glass first. An enabled baseline with an empty break-glass group has no recovery path.

The most likely way to cause an outage

Enabling a location policy while its named location still holds placeholder values. Depending on the policy, that locks out every administrator except break-glass, stops directory sync, or cuts off every meeting room in the building. It's the reason placeholders use documentation-only address ranges that can never match real traffic, and the reason those policies have their own gate.

09

What Microsoft charged me to learn

Half of any real Microsoft project is licensing archaeology. Three platform findings from deploying the full build into a live tenant in September 2026, all of them platform behaviour rather than Terraform quirks, so they apply to any bulk-import method.

Entra ID P2 gates policy creation, not just enforcement

I knew P2 had to be assigned to users in scope before risk-based policies could enforce. I didn't know Graph refuses to create the policy object at all when the tenant holds no P2 SKU whatsoever, regardless of per-user assignment. Four policies simply failed to deploy.

BadRequest: 1039: Cannot create or update policies with premium P2 features

Tenant-level P2 presence became a hard go/no-go gate before deployment starts, rather than a pre-enforcement check.

Workload Identity Premium is a separate add-on, not a higher tier of P2

The service principal risk policy failed with a different error naming workload identity premium specifically. A tenant can hold full P2 and still be unable to create it.

BadRequest: 1149

Large first-time deployments can trip a transient consistency error

Deploying the full set in one batch into a fresh tenant, the two location-referencing policies failed saying the named location didn't exist in the directory. It did. Healthy, correctly typed, visible in the portal. The failure repeated identically after more than an hour, which rules out simple propagation lag.

BadRequest: 1040: NamedLocation ... does not exist in the directory

Retrying those two individually, once the rest of the batch had settled, succeeded cleanly with no change to either object. I've written it up as transient rather than solved, because that's what it is. If it happens again, let the batch finish and retry the individual policy before assuming the location is broken and rebuilding it.

And a few from the Terraform side

10

What this doesn't do

It isn't deployed. Built and validated in a live tenant, with no operational history behind it.

It isn't a replacement for the twelve-policy set in a thirty-person business. Deploying 44 policies and a persona model into a tenant with one administrator is worse than what's already there, not better. The design assumes the operating team that justifies it.

It isn't a compliance certification. It aligns with common security frameworks, Essential Eight, CIS and Microsoft secure-by-default, and certifies against none of them.

It isn't safe to enable as shipped, and it isn't turnkey. Every policy deploys disabled and the location inputs deploy as placeholders, both deliberately. Several prerequisites have to be in place per tenant before anything is enforced, and customer-specific tailoring is expected, captured as variables rather than hand-edits.

It doesn't handle privileged access for guests and contractors, and that's structural rather than an oversight. A guest account can't satisfy the phishing-resistant MFA this design requires of every administrator, so folding them into the persona model would mean weakening it for everyone. Those cases belong outside the baseline, handled individually.

Deliberately out of scope