Terraform Field Guide · Chapter 10 of 12
Terraform in CI/CD
Applying from a laptop works until two laptops disagree. Move Terraform into a pipeline: formatting and validation on every push, a plan posted to every pull request, applies that run environment by environment after merge, and short-lived credentials so no access key ever sits in a repository or on a laptop.
- 50 min
- Advanced
- Hands-on
- Free
By Joshua Sequeira, founding engineer running Terraform in production. Updated .
By the end you can
0 of 5
Live lab in this chapter
A real-feeling terminal and a live cluster map, right in your browser. Every command block below has a ▶ Run in lab button.
Why a pipeline
Applying from laptops has three problems you have already met. Two people can apply at once (chapter 3). What runs depends on whose laptop, which provider version and which uncommitted edits. And every laptop that can apply to production holds credentials that can change production.
A pipeline fixes all three. The code in Git is the only thing that gets applied, it runs in the same clean environment every time, and the credentials live in the pipeline for the length of one run.
The stages
A good Terraform pipeline is a series of gates, cheapest first. Each one catches a different kind of mistake. Pick a change and run it:
Interactive · The pipeline
Open a pull request. Which gate catches it?
- fmt -checkpull request
- validatepull request
- plan, posted as a commentpull request
- policy checkspull request
- human reviewpull request
- apply the saved planafter merge
$ # pick a change, then run the pipelineNotice that no single gate catches everything. Formatting and validation catch carelessness. Policy catches known-bad patterns. Only a person reading the plan catches "this is valid, allowed, and still wrong". And only applying a saved plan guarantees the reviewed plan is the one that runs.
The workflow
Here is the shape in GitHub Actions. Pull requests get checks and a plan comment; pushes to main apply, environment by environment.
name: terraform
on:
pull_request:
paths: ["envs/**", "modules/**"]
push:
branches: [main]
paths: ["envs/**", "modules/**"]
permissions:
id-token: write # OIDC: ask GitHub for a token to trade with AWS
contents: read
pull-requests: write # post the plan as a comment
jobs:
plan:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
environment: dev-plan
defaults:
run:
working-directory: envs/dev
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ vars.PLAN_ROLE_ARN }}
aws-region: eu-west-1
- run: terraform fmt -check -recursive
- run: terraform init -input=false
- run: terraform validate
- run: terraform plan -input=false -no-color -out=tfplan
- run: terraform show -no-color tfplan > plan.txt
- run: gh pr comment ${{ github.event.number }} --body-file plan.txt
env:
GH_TOKEN: ${{ github.token }}
apply-dev:
if: github.event_name == 'push'
runs-on: ubuntu-latest
environment: dev
concurrency: terraform-dev
defaults:
run:
working-directory: envs/dev
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ vars.APPLY_ROLE_ARN }}
aws-region: eu-west-1
- run: terraform init -input=false
- run: terraform plan -input=false -out=tfplan
- run: terraform apply -input=false tfplan
# apply-staging and apply-prod: the same steps, with needs: apply-dev
# (and needs: apply-staging), and environment: prod set to require approval.- Lets the job request an OIDC token. Without it, the AWS step cannot assume a role.
- GitHub environments hold per-environment variables (like PLAN_ROLE_ARN) and protection rules.
- Fails if any file is not formatted. Run terraform fmt locally to fix.
- Saves the exact plan, so the same plan can be shown and applied.
- Posts the plan to the pull request. Tools like Atlantis or HCP Terraform do this with nicer formatting.
- Queues runs per environment, so two merges never apply to dev at once.
- Applies exactly the plan made two lines earlier, with no prompt.
- In the repository settings, give the prod environment required reviewers. The job waits until someone approves.
This version plans again at merge time and applies that plan. That is simple and safe, but the plan applied is not byte-for-byte the plan reviewed. Tools built for this, such as Atlantis, HCP Terraform and Spacelift, apply the reviewed plan itself and lock the environment between plan and apply. Start simple; adopt one when you have several people merging infrastructure every day.
No stored keys: OIDC
The old way was an IAM user with access keys pasted into CI secrets. Those keys never expire, work from anywhere, and leak through logs, forks and former employees. OIDC removes them entirely:
- The job asks GitHub for a signed token that says which repository, branch and environment it is running for.
- The AWS step sends that token to AWS STS with
AssumeRoleWithWebIdentity. - AWS checks the role's trust policy and returns credentials that expire, by default, within an hour.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub": "repo:acme/infrastructure:environment:prod"
}
}
}
]
}- Created once per AWS account: an identity provider pointing at GitHub.
- The audience the AWS action asks for.
- The important line. Only jobs in this repository running in the prod environment can assume this role. A pull request from a fork cannot.
Applying safely
- One environment at a time. Dev, then staging, then prod, each as its own job that needs the previous one (chapter 7).
- A human gate before prod. Required reviewers on the prod environment. They approve after reading the plan for prod, not dev.
- Concurrency per environment. Queue runs instead of letting them fight over the lock.
- Pin the Terraform version.
setup-terraformtakes aterraform_version; match it torequired_versionso CI and laptops agree. - No applies from laptops. Once the pipeline works, remove apply permissions from people's roles. Break-glass access for emergencies, logged and rare.
Hands-on: the pipeline, by hand
Take any folder from an earlier chapter, make a small change (add a page to the chapter 6 module, say), then run every stage in the order CI would:
terraform fmt -check -recursive
terraform init -input=false
terraform validate
terraform plan -input=false -out=tfplan
terraform show tfplan
terraform apply tfplan
Success! The configuration is valid.
...
Plan: 1 to add, 0 to change, 0 to destroy.
Saved the plan to: tfplan
To perform exactly these actions, run the following command to apply:
terraform apply "tfplan"
...
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.fmt -check- Silent and exit code 0 when everything is formatted. Otherwise it lists the files.
-out=tfplan- A binary file. terraform show prints it as text, and -json as JSON for tools.
apply tfplan- No yes prompt: a saved plan is already the approval.
Now make a plan go stale. Save a plan, change state in between, then try to apply the old plan:
terraform plan -out=tfplan -replace=random_pet.server
terraform apply -auto-approve -replace=local_file.inventory
terraform apply tfplan
│ Error: Saved plan is stale
│
│ The given plan file can no longer be applied because the state was changed
│ by another operation after the plan was created.Saved plan is stale- Exactly what protects a pipeline when two merges land close together. Plan again, review again.
Mini mission
Make CI fail for the right reason
Put any earlier chapter's folder in a GitHub repository and add a workflow that runs only fmt -check and validate on pull requests (no cloud credentials needed). Open a pull request with a badly indented file and watch it fail. Then fix it with terraform fmt.
Reveal one safe solution
name: checks
on: pull_request
jobs:
checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- run: terraform fmt -check -recursive
- run: terraform init -backend=false
- run: terraform validateinit -backend=false downloads providers without configuring state, so validate can run with no credentials at all. That is a useful first pipeline for any Terraform repository: free, fast, and it stops a whole class of review comments.
Check yourself
Quiz
0 of 5 answered