When to Automate Infrastructure Provisioning in CI
Automate provisioning in CI once environments repeat or several people change them. Signals, a staged rollout, and Terraform plan and apply steps.
Automate infrastructure provisioning in your CI pipeline once the same environment has to be built more than once, more than one person changes it, or a mistake in it would cost real money or downtime. Before that point a reviewed manual apply is fine. After it, a pipeline that plans on every change and applies only reviewed plans is safer and faster.
This guide is about timing and staging: which signals tell you it is time, what to automate first, and how to add apply steps without handing a build server the keys to production on day one. It assumes you already know what infrastructure as code is. If you need that background, start with our guide to infrastructure as code tools for DevOps.
Key takeaways
- Automate the plan step first. Running
terraform planon every pull request is low risk and catches most surprises before anyone applies anything. - Move to automated apply when environments are rebuilt often, several people touch the code, or drift has already caused an incident.
- Apply only the plan that was reviewed. Terraform's
-outoption saves a plan file thatterraform applycan run later. - Production usually keeps a human approval between plan and apply, even in mature teams.
- Remote state with locking is a precondition for any pipeline apply, because two jobs must never write the same state at once.
- Short-lived cloud credentials (for example OIDC from the CI system) are safer than long-lived keys stored as pipeline secrets.
What "automated provisioning in CI" actually means
The phrase covers a range of setups, and teams often argue past each other because they picture different points on it. At one end, a developer edits Terraform, opens a pull request, and the pipeline only checks formatting and validates syntax. At the other end, a merge to the main branch triggers a plan and an apply against production with no human in the loop. Most healthy teams sit somewhere in between, and they move along the range one environment at a time.
It helps to split the work into four steps that can each be automated on their own schedule:
- Static checks: formatting, validation, linting and policy checks against the code.
- Plan: compute what would change in a real environment and show it to a reviewer.
- Apply: make the change, using the plan that was reviewed.
- Verify: confirm the environment works and has not drifted from the code afterwards.
Asking "when should we automate provisioning?" is really four questions. The answer for static checks is "now". The answer for production apply is "later, and with a gate". The rest of this post walks through the signals for each step.
Signals that it is time to automate
There is no fixed team size or cloud bill at which automation becomes mandatory. The useful signals are about repetition, people and risk.
You rebuild the same environment more than once
The first time you build a staging environment by hand, you learn what it needs. The second time, you discover that you forgot half of it. If you create preview environments per branch, spin up load test stacks, or rebuild a sandbox every sprint, the manual path is already costing you time and producing environments that differ in small ways. That is the clearest signal to put at least plan and apply for non-production into the pipeline.
More than one person changes the infrastructure
With one engineer and a laptop, the state of the world lives in that person's head and terminal history. Once two or three people edit the same code, you need one place where changes are planned, reviewed and recorded. A pull request with a plan attached gives reviewers something concrete to approve, and the pipeline log becomes the audit trail. Running applies from laptops at this stage invites the classic failure: two people apply different versions of the code against the same state.
Drift has already bitten you
If someone has opened a security group in the console "just for a minute" and the next apply quietly reverted it, or worse, did not, you have drift. Automated plans on a schedule surface drift early because the plan shows changes nobody asked for. Our post on why infrastructure drift is a silent killer covers detection in more depth.
Audit or compliance asks who changed what
When an auditor or a security reviewer asks for evidence that production changes were reviewed, "we were careful" is not an answer. A pipeline that records the plan, the approver and the apply output for each change is the evidence. If your organisation has change management requirements, automation usually makes meeting them easier rather than harder.
Releases wait on infrastructure tickets
If application teams regularly wait days for a queue, a bucket or a DNS record because one platform engineer has to run the change, the bottleneck is the manual apply. Self-service through pull requests, with the platform team reviewing plans instead of typing commands, removes the wait without removing control.
When manual provisioning is still reasonable
Automation has a setup cost, and it is fair to delay it in a few cases. A proof of concept that will be thrown away in two weeks does not need a pipeline. A one-off migration, such as importing existing resources into state, is often easier to run by hand with careful review, then hand over to the pipeline once the code matches reality. Very early projects with a single engineer can run applies locally as long as state is already remote and locked, so the switch to CI later is painless.
The mistake is letting "temporary" manual steps become permanent. A good rule is to write down, at the start, the trigger that will move each environment into the pipeline: the second engineer joining, the first customer, the first compliance review. When the trigger fires, do the work.
A staged rollout that keeps risk low
Teams that try to automate everything at once tend to give the pipeline broad production credentials before they trust it. A staged rollout avoids that.
Stage 1: static checks on every pull request
Run formatting and validation, plus any linting or policy tools you use. These need no cloud credentials, run in seconds and stop broken code before review. For Terraform, terraform fmt -check and terraform validate are the usual starting points.
Stage 2: plan on every pull request
Give the pipeline read access to the target environment and run a plan, then post the summary to the pull request. Reviewers now approve a concrete diff of infrastructure, not just a diff of code. Terraform's -input=false option disables interactive prompts for unset variables, which the documentation describes as useful in non-interactive automation. The -detailed-exitcode option returns 0 when there are no changes, 1 on error and 2 when changes are present, which lets a pipeline label pull requests or skip later steps.
Stage 3: automated apply for non-production
Once plans are trusted, let a merge to the main branch apply to development and staging. Save the plan with -out, keep it as a pipeline artifact, and apply that exact file. The Terraform documentation notes that the saved plan contains the full configuration and input variables, so store it as you would a secret and delete it after use.
Stage 4: gated apply for production
For production, keep the same plan and apply flow but put an approval between them. Most CI systems support protected environments or manual approval jobs for this. The approver reads the saved plan and approves the apply of that plan, not a fresh one computed minutes later against a world that may have changed.
Stage 5: scheduled drift checks
Run a plan on a schedule against each environment and alert when it shows changes. The -refresh-only mode creates a plan that only updates state to match changes made outside Terraform, which helps when you want to see drift without proposing fixes.
Decision table by environment
| Environment | Plan in CI | Apply in CI | Human approval |
|---|---|---|---|
| Ephemeral or preview | Yes | Yes, on branch push | No |
| Development | Yes | Yes, on merge | Usually no |
| Staging | Yes | Yes, on merge | Optional |
| Production | Yes | Yes, from saved plan | Yes |
| Shared foundations (network, identity) | Yes | Often manual trigger | Yes, two reviewers |
A minimal pipeline sketch
The exact syntax depends on your CI tool, but the shape is the same everywhere. This shell sequence shows the core commands a job runs:
terraform init -input=false
terraform fmt -check
terraform validate
terraform plan -input=false -out=tfplan -detailed-exitcode
# exit code 2 means changes are present; publish tfplan as an artifact
# later, in a separate approved job:
terraform apply -input=false tfplan
Keep the plan job and the apply job separate. The plan job can run with read permissions on every pull request. The apply job runs only on the main branch, only after approval for protected environments, and uses a role with write permissions.
Preconditions you need before any automated apply
Remote state with locking
A pipeline that applies changes must read and write a shared state, and it must stop two jobs from writing at once. Use a remote backend that supports locking. Our explainer on Terraform remote state, backends and locking goes through the options.
Credentials that expire
Long-lived access keys pasted into CI secrets are the most common weak spot in provisioning pipelines. Most major CI systems can now request short-lived cloud credentials through OpenID Connect, which removes the stored key entirely. Scope the plan role to read and the apply role to the resources that pipeline manages.
One pipeline per state
Map each state file to exactly one pipeline. If two pipelines can apply to the same state, you will eventually get conflicting changes and confusing locks.
Clear ownership of modules
Shared modules need owners and versioning. When a module changes, the pipelines that consume it should pick up the new version on purpose, through a version bump in a pull request, not silently on the next run.
Common mistakes when teams automate too early or too late
Automating too early usually looks like a pipeline with admin credentials and no review step, built before anyone understood the infrastructure. When it fails, nobody knows whether the code or the pipeline is wrong. The fix is to slow down to the staged rollout above.
Automating too late looks like a team where every engineer has production credentials on a laptop, applies happen at odd hours, and the state file has been force-unlocked more than once. The fix is to pick one environment, usually staging, and move it fully into CI this sprint.
A third mistake is automating apply but not plan review. If the pipeline applies whatever the main branch says without anyone reading the plan, you have only moved the risk from a laptop to a server. The value of CI provisioning comes from the reviewed plan, more than from the automation of the apply itself.
A fourth is treating provisioning and application deployment as one job. They change at different rates and fail in different ways. Many teams keep infrastructure pipelines separate from application release pipelines, and connect them through outputs or events. The keeper post in this topic, on event-driven architectures for real-time DevOps pipelines, shows how events can trigger downstream work once infrastructure is ready.
Where quality and policy gates fit
Once plan runs in CI, it becomes the natural place for policy checks: blocking public storage buckets, requiring tags, limiting instance sizes. Put these checks between plan and apply so they evaluate the actual planned change. Start with a few rules that reflect real incidents, and run new rules in warning mode before you enforce them. For general advice on gates, see when to add quality gates to a CI pipeline.
How this fits the wider DevOps workflow
Provisioning in CI is one part of a broader loop: write code, review a plan, apply, observe, and feed what you learn back into the code. Our walkthrough of Terraform in the DevOps workflow follows a change from plan to apply. If you are still deciding how to model resources, the difference between declarative and imperative IaC affects how plans behave in a pipeline.
If you want structured practice building these pipelines, our Terraform training is taught in the Kharadi, Pune classroom and live online.
A short checklist before you flip the switch
- State is remote, locked and backed up.
- The pipeline uses short-lived credentials, with separate plan and apply roles.
- Every pull request shows a plan summary to reviewers.
- Apply uses the saved, reviewed plan file.
- Production apply needs an approval from someone other than the author.
- A scheduled plan alerts on drift.
- Someone owns the pipeline and gets paged when it breaks.
If every item is true for an environment, that environment is ready for automated apply. If two or more are false, fix those first. The order matters less than finishing them, because each one closes a specific way that automated provisioning can go wrong.
Frequently asked questions
Should every infrastructure change go through CI?
Every change to shared or long-lived environments should, so there is one reviewed record of it. Throwaway experiments and one-off imports can be done by hand, as long as the result is brought back into code and the pipeline afterwards.
Is it safe to auto-apply to production?
Some mature teams do it, but most keep a human approval between a saved plan and the apply. Start with approval, measure how often approvers catch problems, and only remove the gate if the data supports it.
What should run on a pull request?
Formatting, validation, policy checks and a plan against the target environment. The plan summary should be posted to the pull request so reviewers approve real infrastructure changes, not only code.
Why save the plan with -out?
A saved plan lets you apply exactly what was reviewed. Without it, apply computes a fresh plan that may differ if the environment changed in between. Treat the plan file as sensitive because it contains configuration and variables.
How do I detect drift automatically?
Schedule a plan against each environment and alert when it reports changes. Terraform's refresh-only mode shows changes made outside Terraform without proposing to undo them.
Do I need remote state before automating?
Yes. A pipeline needs shared state that every job reads, and locking so two jobs never write it at the same time. Local state on a runner disappears when the job ends.
How should the pipeline authenticate to the cloud?
Prefer short-lived credentials issued through OpenID Connect over stored access keys. Use a read role for plan jobs and a narrower write role for apply jobs.
References
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0