Lesson 12 of 14 · 18m
Terraform in CI: Plan on PR, Apply on Merge
Plan output posted on the PR is the review; OIDC role assumption replaces stored access keys; saved plan files are secrets too.
At some point "who runs terraform apply" stops being "whoever has the repo checked out" and becomes a pipeline question — because laptops hold credentials, laptops go offline mid-apply, and a review process that ends at "someone ran plan on their machine" isn't a process.
The pipeline shape
PR opened → fmt → validate → tflint/checkov → plan → plan output posted on the PR
PR merged → apply against the environment backend (serialized by the state lock)terraform fmt -checkandvalidateare the free gates — syntax and schema errors die in seconds.- Static analysis —
checkov,trivy config,tflint— flags the policy violations humans miss at 200 lines of diff:0.0.0.0/0on port 22, unencrypted storage, missing logging. More on the policy layer in its own lesson. terraform plan -out=plan.tfplanin the PR job, output posted as a comment or artifact. Reviewers approve the diff, not the intention.terraform apply plan.tfplanon merge — the saved plan ensures the thing that runs is the thing that was reviewed.-detailed-exitcodelets the apply job skip cleanly when the merge produced no diff.- Drift detection runs on a schedule: a nightly
plan -detailed-exitcodeagainst prod. Exit code 2 means reality diverged from code — someone clicked, or something changed upstream. That's an alarm, filed automatically.
Atlantis is the open-source tool that productized this workflow — PR comments trigger plan, approval triggers apply, all serialized through the state lock. HCP Terraform, Spacelift, and env0 sell the same shape hosted. The mechanics are identical regardless of vendor: plan on PR, apply on merge, lock prevents concurrent writes.
Authentication: OIDC or go home
The pipeline needs cloud credentials, and the wrong answer is still the common one: a long-lived AKIA... access key stored in GitHub secrets. Stored keys leak — the 2021 Codecov incident exfiltrated CI credentials en masse through a modified bash uploader, and a leaked AKIA key is valid until someone notices.
The right answer is OIDC federation — the CI job exchanges its own signed identity token for short-lived cloud credentials:
# .github/workflows/terraform.yml
permissions:
id-token: write # lets the job mint an OIDC token
contents: read
steps:
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/terraform-ci
aws-region: us-east-1The AWS side is an IAM role with a trust policy on token.actions.githubusercontent.com — scoped to your repo, your branch, sometimes your environment. No stored secrets, credentials that expire in minutes, and a trust policy that says exactly which CI jobs may assume the role. GitLab (id_tokens), CircleCI, and Azure all implement the same OIDC pattern; the role-trust-policy shape is universal.
The artifacts are secrets too
plan.tfplan files contain resolved values — everything apply will see, including masked-in-CLI sensitive attributes. Store them as CI artifacts with the same access controls as state; never commit them. Same for terraform show -json output piped to policy tools — the JSON is a plaintext dump of your intended infrastructure. CI job logs that echo plan output inherit the same exposure.
Who applies, in the end
The pipeline owns the apply; humans own the merge. That separation is the audit trail — every infrastructure change maps to a reviewed PR, a recorded plan, and a logged apply. The laptop path doesn't vanish — terraform import, state surgery, debugging — but routine changes that bypass the pipeline are drift by definition.
Field notes
- Pin the Terraform version in CI —
hashicorp/setup-terraformwithterraform_version: 1.12.x— because HCL behavior shifts between minors and your state file is picky about versions. applyjobs should be serialized per environment; the state lock is the enforcement, but pipeline concurrency groups make it orderly instead of racy.- A failed apply mid-run leaves resources created and state updated — the next
plancontinues from where it stopped. Re-running is safe; panicking and clicking is not.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
AWS Emulator Puts AWS on Your Laptop. Keep Your IAM Tests Off It.
AWS released AWS Emulator on November 11, a free local server that answers AWS API calls on 127.0.0.1 with per-run keys and fresh certificates.
What is Infrastructure as a Service? The Layer That Makes Everything Else Possible
Infrastructure as a Service gives you virtualized servers, storage, and networking on demand without owning any hardware. You rent compute and own everything that runs on it. Here is what IaaS actually is, what it demands from you.
What is Platform as a Service? The Sweet Spot Between "Too Easy" and "Too Much Work"
Platform as a Service sits between raw servers and fully managed software. You push code, the platform runs it. No Nginx config, no OS patches, no 3 AM server alerts. Here is what PaaS actually gives you, what it costs you in control, and how to decide if it is the right layer for your application.
The World now is Serverless and Container based
A new report from Datadog reveals that serverless computing could be entering the mainstream. This has already been the case in my world for the past few years. Results show that more than half of all organizations are using serverless on one of the three major public cloud providers: Amazon,