// Why this matters
If you want to speed up a Terraform plan for thousands of group members, the answer is rarely a faster runner. It is changing what Terraform is asked to track. A directory with a couple of thousand memberships modelled as one resource each spends nearly all of its time refreshing objects that have not changed.
Slow plans have a second-order cost: people stop running them. A weekly drift check that takes forty minutes and flakes on throttling is a drift check nobody reads. Fast, boring plans are what make "the config is the truth" a claim you can actually defend.
This article is the performance and safety companion to One Config, Two Clouds: Group and Role Management as Code: same stack, but focused on how it behaves once it is big.
// The problem
The original design created one azuread_group_member per (group, user) pair. At roughly two thousand three hundred of those, every plan issued thousands of individual Graph reads, hit throttling, and routinely failed halfway. Retries made it slower still, and a partial refresh produced misleading diffs.
Eligible (just-in-time) role assignments made it worse. Their status lives behind a different API, has no bulk data source in the provider, and has a nasty property: if a user has activated an eligibility, naive reconciliation sees a changed assignment and tries to undo it.
Finally, there were operational rules. Two overlapping runs must never interleave writes, an apply must run exactly what was reviewed, and a failed scan or plan must not look like "no changes". Without these, speed is just a faster way to cause an incident.
// The solution
Replace many tiny resources with a small number of bulk ones. One data source reads the full membership of each managed group in a single paginated call, and the config computes the set difference: members to add and members to remove. Only the difference becomes imperative work, driven by a resource whose triggers are the computed sets.
For eligibility, a bash script runs as a Terraform external data source. It receives the list of (group, user) pairs, queries the PIM schedule APIs through the Graph $batch endpoint in chunks of 20, follows @odata.nextLink until exhausted, and retries on 429 and 5xx with backoff. It returns a flat JSON map of what already exists.
PIM reconciliation is intentionally add-only. Revoking eligibility is high impact and ambiguous (did the user activate, or was the assignment removed?), so the script only creates what is missing. A miss costs one redundant add on the next run, which is idempotent and harmless. Members who have activated are ignored through lifecycle rules so activation is not undone.
The pipeline treats the plan exit code as a three-way branch (0 nothing, 1 failure, 2 changes), serialises runs with a concurrency group that never cancels, and applies the saved plan file. I rejected splitting into many smaller stacks: it would have made each plan faster but taken the global view and the single review path away (see One Config, Two Clouds: Group and Role Management as Code).
- Triggerpush to main (path filtered), weekly cron or manual dispatch
- Keyless authOIDC login to Azure and Google via workload identity federation
- Static checksfmt, init, validate, lint and scan
- Planhigher parallelism for read waves; exit code interpreted
- Branch on result gate0 no change, 1 fail, 2 changes
- Reportmarkdown summary, plan artifacts, colour-coded chat message
- Approval gateapply bound to a protected environment
- Applythe exact saved plan, with lower parallelism for writes
- Notifysuccess or failure message
- Triggerpush (path filtered), weekly cron, manual dispatch
- Keyless loginOIDC to both clouds
- Static checksfmt, validate, TFLint, Checkov
- Plandetailed exit code, high parallelism for reads
- Branch gate0 stop, 1 fail loud, 2 continue
- Reportmarkdown summary and plan artifact
- Approval gateprotected environment
- Applysaved plan, low parallelism for writes
// Before you start
- Terraform 1.5+ with the azuread and external providers
- bash 4+, curl and jq on the runner (self-hosted runners near the APIs help latency)
- A service principal with Group.Read.All and the PIM read/write permissions it needs, authenticated by workload identity federation (see The App Registration Factory That Cannot Hold a Secret)
- GitHub Actions with a protected environment and runner labels you control
- Basic familiarity with the Graph batch format and OData paging
// Step-by-step implementation
01 Replace per-member resources with a bulk read and a diff
Read each managed group once and compute the delta in locals. The
azuread_groupdata source returns the full member object ID list, so a thousand members cost one call instead of a thousand.Everything downstream consumes
to_addandto_remove. If both are empty the plan has nothing to do, regardless of group size.02 Write the Graph batch reader with pagination and retry
Graph
$batchaccepts up to 20 sub-requests and returns per-request status codes. Throttled items come back as 429 inside a 200 batch response, so you must inspect each item, not the HTTP status of the envelope.The script keeps a work queue: send 20, collect the successes, requeue the 429 and 5xx items after sleeping for the largest
Retry-Aftervalue seen, and give up on any item after five attempts. Pagination is handled per item by following@odata.nextLinkuntil it disappears.03 Call it from Terraform and make PIM add-only
The
externaldata source passes values as strings, so JSON-encode the pairs and decode the result. Then create only the eligibilities the script reported as absent.Add-only is encoded structurally: there is no destroy path for the resource because it is created from a diff that can only contain missing items, and
ignore_changescovers fields that move when a user activates.04 Trigger on push, weekly and on demand, and queue runs
Three triggers share one workflow. Push is path filtered so unrelated commits do not run it. The weekly cron runs plan only, because its job is to surface drift, not to change anything. Manual dispatch carries an input to choose plan-only.
The concurrency group is the key safety property:
cancel-in-progress: falsemeans a second run queues instead of killing the first mid-apply. A cancelled apply can leave a state lock and a half-written change; queuing is always safer for infrastructure.05 Authenticate without secrets and run static checks
Login uses OIDC federation to both clouds, so there is no stored credential to leak or rotate. The federated credential on the cloud side is pinned to the repository and the environment, which is what makes this safe (the pattern is in The App Registration Factory That Cannot Hold a Secret).
Run format, validate, TFLint and Checkov before the plan. They are cheap and they fail with better messages than a provider would.
06 Plan with tuned parallelism and interpret the exit code
Reads are cheap and independent, so plan with a high
-parallelism. Writes during apply are the ones that trigger throttling and ordering problems, so apply with a low value. This one tuning, split by phase, removed most of our flakiness.Branch explicitly on the exit code. A script that treats any non-zero as "changes" will happily apply after a failed plan, and one that treats it as "failure" will never apply at all.
07 Gate the apply and run exactly the reviewed plan
The apply job needs the plan job, only runs when the exit code is 2 and the run is not plan-only, and is bound to a protected environment with required reviewers. The reviewer sees the same plan summary as the artifact.
It downloads the saved plan and applies that file. Applying with
-parallelism=5keeps write throttling away, and because the plan file is applied verbatim, nothing can change between review and apply.
// How to verify it works
- On unchanged main, trigger the workflow manually: plan exit code 0, apply job shown as skipped.
- Time
terraform planbefore and after the bulk read change on the same data: refresh should shrink from thousands of calls to roughly one per group. - Run the PIM script by hand with a two-pair JSON input: it must print a JSON object keyed by index with "true" or "false", and exit 0.
- Force throttling by lowering the chunk size sleep and replaying; the script must retry and still return a complete result, never a partial one.
- Push two commits close together: the second run must show as queued, not cancelled.
// Design decisions and trade-offs
- Concurrency group with cancel-in-progress off, so runs queue and never abort mid-apply.
- PIM membership handling is add-only: it never revokes high-tier eligibility, and a miss costs only a redundant add next run.
- Members who activated eligibility are ignored via lifecycle rules so activation is not undone.
- Pagination follows next-links to exhaustion; transient errors retry up to five times with backoff.
- Runs on a network-close self-hosted runner pool for API latency.
// Pitfalls and lessons learned
- Batch envelopes return HTTP 200 even when individual items are throttled. Check each item status or you will treat missing data as "absent" and re-add everything.
- The external data source can only return a map of strings. Encode booleans as the strings "true" and "false" and compare accordingly.
- Cancelling an in-progress apply leaves a state lock. Keep
cancel-in-progressoff for the apply path. - Users who activated an eligibility look like drift. Without
ignore_changesthe next apply deactivates them mid-task. - A high
-parallelismis great for refresh and terrible for writes; set them separately per phase. - Scheduled runs inherit the default branch, so a drift check on a stale protected branch can lie. Pin the ref explicitly.
// Frequently asked questions
How do I speed up a slow Terraform plan with many resources?
Cut the number of tracked resources: read in bulk with data sources, reconcile only the difference, and keep per-item resources for things that genuinely need them. Raise -parallelism for reads, not writes.
What does terraform plan -detailed-exitcode return?
0 for no changes, 1 for an error and 2 when there are changes. Branch on all three in CI.
When should I use the Terraform external data source?
When no provider data source exists and you need a read-only lookup. Keep it idempotent, side-effect free and fast, and return a flat map of strings.
Why not cancel in-progress runs?
Cancelling mid-apply can leave a half-applied change and a held state lock. Queueing is safe and usually fast enough.
Can I run a drift check without applying?
Yes: a scheduled workflow that runs plan only and posts the result. Exit code 2 on schedule means someone changed things outside the config.
// The outcome
About 2,300 per-member resources replaced by bulk reads; batches of 20 per Graph call; weekly drift check.
// Where to take it next
- Alert on exit code 2 from the scheduled run so drift pages somebody instead of waiting for the next review.
- Cache the user ID resolution between runs to shave the remaining lookups.
- Add a plan-size guard that fails the run if the diff touches more than a configured number of memberships.
- Read One Config, Two Clouds: Group and Role Management as Code for the data model this pipeline operates on.