Terraform Labs · Lab 9 of 9
Production: Multi-Environment Layout and a CI/CD Pipeline
Put it all together the way teams run Terraform in production: a tested module, one root per environment with its own account, backend and variables, GitHub OIDC roles instead of stored keys, and a GitHub Actions pipeline that plans every pull request and applies reviewed plans to dev, then to prod after approval.
- Environment
- Production
- Level
- Advanced
- Time
- About 90 min
- Cost
- A few cents (S3, SSM, IAM); Actions free on public repos
You will build
A repository you could hand to a team: nobody runs terraform apply from a laptop, every change is planned
in a pull request, and production changes need an approval.
Before you start
- Lab: Write a Module and Test It with terraform test
- Lab: AWS: Remote State in S3 with Locking
Two AWS accounts (dev and prod) — or one account used twice while practising
A GitHub repository you administer
This lab is about structure and process more than resources. The infrastructure is deliberately small — an artifacts bucket and an SSM parameter per environment — so you can focus on the layout, identities and pipeline that make any Terraform codebase safe to change.
The example account IDs 111111111111 (dev) and 222222222222 (prod) and the repository
acme/platform-infra stand in for yours.
The layout
modules/app-storage is the reusable, tested code. envs/dev and envs/prod are thin roots that
call it with their own terraform.tfvars and backend.tf. Each environment lives in its own AWS account
with its own state bucket, so a mistake in dev can't touch prod's resources or state.
Project structure
platform-infra/
├── .gitignore
├── .github/
│ └── workflows/
│ └── terraform.yml # checks, plan per environment, apply dev → prod
├── bootstrap/
│ └── github-oidc/
│ └── main.tf # once per account: OIDC provider, plan and apply roles
├── modules/
│ └── app-storage/
│ ├── versions.tf
│ ├── variables.tf
│ ├── main.tf
│ ├── outputs.tf
│ └── tests/
│ └── app_storage.tftest.hcl
└── envs/
├── dev/
│ ├── main.tf # identical in every environment
│ ├── backend.tf # dev account's state bucket
│ └── terraform.tfvars # dev values
└── prod/
├── main.tf
├── backend.tf
└── terraform.tfvars
Steps
-
1Why this layout
modules/holds the reusable code, tested on its own.envs/<name>/are thin root modules: the samemain.tfeverywhere, with differences only interraform.tfvarsandbackend.tf. Each environment has its own state, its own account and its own credentials, so a mistake in dev can't reach prod.bootstrap/holds the few things created once by an administrator: state buckets (previous lab) and the identities CI uses.
-
2Module: versions
Reusable modules set a minimum and maximum provider version; the root modules pick the exact one.
modules/app-storage/versions.tf terraform { required_version = ">= 1.10" required_providers { aws = { source = "hashicorp/aws" version = ">= 6.0, < 7.0" } } } -
3Module: inputs
modules/app-storage/variables.tf variable "project" { description = "Short project name" type = string } variable "environment" { description = "dev, staging or prod" type = string validation { condition = contains(["dev", "staging", "prod"], var.environment) error_message = "environment must be dev, staging or prod." } } variable "name_suffix" { description = "Makes bucket names globally unique, e.g. the AWS account ID" type = string } variable "noncurrent_version_days" { description = "How long to keep old object versions" type = number default = 30 validation { condition = var.noncurrent_version_days >= 1 && var.noncurrent_version_days <= 3650 error_message = "noncurrent_version_days must be between 1 and 3650." } } -
4Module: resources
Production rules live in the module, so every environment gets them: encryption, blocked public access, version expiry, and
force_destroyonly outside prod.modules/app-storage/main.tf locals { bucket_name = "${var.project}-${var.environment}-artifacts-${var.name_suffix}" } resource "aws_s3_bucket" "artifacts" { bucket = local.bucket_name force_destroy = var.environment != "prod" # prod buckets can't be deleted while they hold objects } resource "aws_s3_bucket_versioning" "artifacts" { bucket = aws_s3_bucket.artifacts.id versioning_configuration { status = "Enabled" } } resource "aws_s3_bucket_server_side_encryption_configuration" "artifacts" { bucket = aws_s3_bucket.artifacts.id rule { apply_server_side_encryption_by_default { sse_algorithm = "aws:kms" } bucket_key_enabled = true } } resource "aws_s3_bucket_public_access_block" "artifacts" { bucket = aws_s3_bucket.artifacts.id block_public_acls = true block_public_policy = true ignore_public_acls = true restrict_public_buckets = true } resource "aws_s3_bucket_lifecycle_configuration" "artifacts" { bucket = aws_s3_bucket.artifacts.id rule { id = "expire-old-versions" status = "Enabled" filter {} noncurrent_version_expiration { noncurrent_days = var.noncurrent_version_days } } } # Applications read the bucket name from here instead of hard-coding it resource "aws_ssm_parameter" "bucket_name" { name = "/${var.project}/${var.environment}/artifacts-bucket" type = "String" value = aws_s3_bucket.artifacts.bucket } -
5Module: outputs
modules/app-storage/outputs.tf output "bucket_name" { description = "Name of the artifacts bucket" value = aws_s3_bucket.artifacts.bucket } output "bucket_arn" { description = "ARN of the artifacts bucket, for IAM policies" value = aws_s3_bucket.artifacts.arn } -
6Module tests with a mocked provider
mock_provider "aws" {}lets the tests run without any AWS credentials, so they run in seconds on every pull request.modules/app-storage/tests/app_storage.tftest.hcl # Runs without AWS credentials: the mock provider invents computed values mock_provider "aws" {} variables { project = "shop" environment = "dev" name_suffix = "123456789012" } run "bucket_name_follows_convention" { command = plan assert { condition = aws_s3_bucket.artifacts.bucket == "shop-dev-artifacts-123456789012" error_message = "Bucket name must be <project>-<environment>-artifacts-<suffix>." } } run "prod_bucket_cannot_be_force_destroyed" { command = plan variables { environment = "prod" } assert { condition = aws_s3_bucket.artifacts.force_destroy == false error_message = "Production buckets must not allow force_destroy." } } run "public_access_is_blocked" { command = plan assert { condition = aws_s3_bucket_public_access_block.artifacts.block_public_policy && aws_s3_bucket_public_access_block.artifacts.restrict_public_buckets error_message = "Public access must be blocked." } } run "rejects_unknown_environment" { command = plan variables { environment = "qa" } expect_failures = [var.environment] } -
7Run the module tests
Run cd modules/app-storage terraform init -backend=false terraform testExpected output
tests/app_storage.tftest.hcl... in progress run "bucket_name_follows_convention"... pass run "prod_bucket_cannot_be_force_destroyed"... pass run "public_access_is_blocked"... pass run "rejects_unknown_environment"... pass tests/app_storage.tftest.hcl... tearing down tests/app_storage.tftest.hcl... pass Success! 4 passed, 0 failed.
-
8Environment root
Copy this file to
envs/dev/main.tfandenvs/prod/main.tfunchanged.allowed_account_idsmakes Terraform refuse to run if your credentials point at the wrong account — the cheapest protection against applying prod code to dev, or the reverse.envs/dev/main.tf (and envs/prod/main.tf) terraform { required_version = ">= 1.10" required_providers { aws = { source = "hashicorp/aws" version = "~> 6.0" } } } provider "aws" { region = var.region allowed_account_ids = [var.account_id] # refuses to run against any other account default_tags { tags = { Project = var.project Environment = var.environment ManagedBy = "terraform" Repository = "acme/platform-infra" } } } variable "region" { type = string } variable "account_id" { type = string } variable "project" { type = string } variable "environment" { type = string } variable "noncurrent_version_days" { type = number } module "app_storage" { source = "../../modules/app-storage" project = var.project environment = var.environment name_suffix = var.account_id noncurrent_version_days = var.noncurrent_version_days } output "artifacts_bucket" { value = module.app_storage.bucket_name } -
9Dev values
envs/dev/terraform.tfvars region = "us-east-1" account_id = "111111111111" # dev account project = "shop" environment = "dev" noncurrent_version_days = 7 -
10Prod values
envs/prod/terraform.tfvars region = "us-east-1" account_id = "222222222222" # prod account project = "shop" environment = "prod" noncurrent_version_days = 90 -
11Dev backend
Each environment's state lives in its own account's state bucket (created as in the previous lab).
envs/dev/backend.tf terraform { backend "s3" { bucket = "acme-tfstate-111111111111-us-east-1" # state bucket in the dev account key = "platform-infra/dev/app.tfstate" region = "us-east-1" encrypt = true use_lockfile = true } } -
12Prod backend
envs/prod/backend.tf terraform { backend "s3" { bucket = "acme-tfstate-222222222222-us-east-1" # state bucket in the prod account key = "platform-infra/prod/app.tfstate" region = "us-east-1" encrypt = true use_lockfile = true } } -
13Plan dev from your computer once
With credentials for the dev account, check that the environment plans before handing it to CI.
Run cd envs/dev terraform init terraform planExpected output
Initializing modules... - app_storage in ../../modules/app-storage ... # module.app_storage.aws_s3_bucket.artifacts will be created + resource "aws_s3_bucket" "artifacts" { + bucket = "shop-dev-artifacts-111111111111" + force_destroy = true ... # module.app_storage.aws_s3_bucket_lifecycle_configuration.artifacts will be created ... + noncurrent_days = 7 ... # module.app_storage.aws_s3_bucket_public_access_block.artifacts will be created # module.app_storage.aws_s3_bucket_server_side_encryption_configuration.artifacts will be created # module.app_storage.aws_s3_bucket_versioning.artifacts will be created # module.app_storage.aws_ssm_parameter.bucket_name will be created ... + name = "/shop/dev/artifacts-bucket" ... Plan: 6 to add, 0 to change, 0 to destroy. Changes to Outputs: + artifacts_bucket = "shop-dev-artifacts-111111111111"Check:Now try
cd ../prod && terraform init && terraform planwith the same dev credentials: it stops with an "AWS account ID not allowed" error. That's the guard working. -
14Identities for CI: OIDC roles
GitHub Actions can prove who it is to AWS with a short-lived OIDC token, so the repository stores no AWS keys. Each account gets two roles:
- plan: read-only, trusted for pull requests and
main; - apply: can change resources, trusted only for jobs running in the matching GitHub environment — which is where the approval rule lives.
The job asks GitHub's OIDC provider for a signed token, which
permissions: id-token: writeallows. The token's claims say which repository, branch or environment is asking (sub) and who it is for (aud). AWS STS checks the token against the account's OIDC identity provider and the IAM role's trust policy, then returns temporary credentials that expire within an hour. Each account has a read-only plan role and an apply role that only jobs in the matching GitHub environment can assume.OIDC: GitHub proves which repository and environment is asking, AWS hands out short-lived credentials bootstrap/github-oidc/main.tf # Run once per AWS account, by an administrator, with local or separate state. # Creates the GitHub OIDC identity provider and two roles for this environment: # plan - read-only, usable from pull requests and main # apply - can change resources, usable only by jobs in the matching GitHub environment terraform { required_version = ">= 1.10" required_providers { aws = { source = "hashicorp/aws" version = "~> 6.0" } } } provider "aws" { region = "us-east-1" } variable "environment" { description = "dev or prod: the GitHub environment allowed to use the apply role" type = string } variable "github_repository" { description = "owner/name of the repository, e.g. acme/platform-infra" type = string } variable "state_bucket_name" { type = string } variable "project" { type = string default = "shop" } locals { oidc_host = "token.actions.githubusercontent.com" } resource "aws_iam_openid_connect_provider" "github" { url = "https://${local.oidc_host}" client_id_list = ["sts.amazonaws.com"] } data "aws_iam_policy_document" "plan_trust" { statement { actions = ["sts:AssumeRoleWithWebIdentity"] principals { type = "Federated" identifiers = [aws_iam_openid_connect_provider.github.arn] } condition { test = "StringEquals" variable = "${local.oidc_host}:aud" values = ["sts.amazonaws.com"] } condition { test = "StringLike" variable = "${local.oidc_host}:sub" values = [ "repo:${var.github_repository}:pull_request", "repo:${var.github_repository}:ref:refs/heads/main", ] } } } data "aws_iam_policy_document" "apply_trust" { statement { actions = ["sts:AssumeRoleWithWebIdentity"] principals { type = "Federated" identifiers = [aws_iam_openid_connect_provider.github.arn] } condition { test = "StringEquals" variable = "${local.oidc_host}:aud" values = ["sts.amazonaws.com"] } condition { test = "StringEquals" variable = "${local.oidc_host}:sub" values = ["repo:${var.github_repository}:environment:${var.environment}"] } } } data "aws_iam_policy_document" "state" { statement { actions = ["s3:ListBucket"] resources = ["arn:aws:s3:::${var.state_bucket_name}"] } statement { actions = ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"] resources = ["arn:aws:s3:::${var.state_bucket_name}/platform-infra/*"] } } data "aws_iam_policy_document" "manage_app" { statement { actions = ["s3:*"] resources = [ "arn:aws:s3:::${var.project}-${var.environment}-*", "arn:aws:s3:::${var.project}-${var.environment}-*/*", ] } statement { actions = ["ssm:*"] resources = ["arn:aws:ssm:*:*:parameter/${var.project}/${var.environment}/*"] } statement { actions = ["ssm:DescribeParameters"] resources = ["*"] } } resource "aws_iam_role" "plan" { name = "github-${var.environment}-plan" assume_role_policy = data.aws_iam_policy_document.plan_trust.json max_session_duration = 3600 } resource "aws_iam_role_policy_attachment" "plan_read_only" { role = aws_iam_role.plan.name policy_arn = "arn:aws:iam::aws:policy/ReadOnlyAccess" } resource "aws_iam_role_policy" "plan_state" { name = "terraform-state" role = aws_iam_role.plan.id policy = data.aws_iam_policy_document.state.json } resource "aws_iam_role" "apply" { name = "github-${var.environment}-apply" assume_role_policy = data.aws_iam_policy_document.apply_trust.json max_session_duration = 3600 } resource "aws_iam_role_policy" "apply_state" { name = "terraform-state" role = aws_iam_role.apply.id policy = data.aws_iam_policy_document.state.json } resource "aws_iam_role_policy" "apply_app" { name = "manage-app-resources" role = aws_iam_role.apply.id policy = data.aws_iam_policy_document.manage_app.json } output "plan_role_arn" { value = aws_iam_role.plan.arn } output "apply_role_arn" { value = aws_iam_role.apply.arn } - plan: read-only, trusted for pull requests and
-
15Plan the bootstrap for one account
Run this as an administrator of each account, with that account's environment name.
Run cd bootstrap/github-oidc terraform init terraform plan -var environment=prod \ -var github_repository=acme/platform-infra -var state_bucket_name=acme-tfstate-222222222222-us-east-1Expected output
# data.aws_iam_policy_document.apply_trust will be read during apply # (config refers to values not yet known) ... # data.aws_iam_policy_document.plan_trust will be read during apply # (config refers to values not yet known) ... # aws_iam_openid_connect_provider.github will be created # aws_iam_role.apply will be created # aws_iam_role.plan will be created # aws_iam_role_policy.apply_app will be created # aws_iam_role_policy.apply_state will be created # aws_iam_role_policy.plan_state will be created # aws_iam_role_policy_attachment.plan_read_only will be created ... Plan: 7 to add, 0 to change, 0 to destroy.
Check:After
terraform apply, note theplan_role_arnandapply_role_arnoutputs. Repeat for dev. -
16Configure GitHub
In the repository settings:
- Environments: create
devandprod. Forprod, add required reviewers and limit deployments to themainbranch. - Variables (Settings → Secrets and variables → Actions → Variables):
DEV_PLAN_ROLE_ARN,DEV_APPLY_ROLE_ARN,PROD_PLAN_ROLE_ARN,PROD_APPLY_ROLE_ARN. Role ARNs aren't secrets. - Branch protection on
main: require pull requests, a review and thechecksandplanjobs to pass.
Check:Both environments exist, and
prodshows its required reviewers. - Environments: create
-
17The pipeline
- checks: formatting and module tests, no cloud access.
- plan: one job per environment with the read-only role; the plan is written to the job summary
so reviewers read it next to the code. On
main, the plan file is kept as an artifact. - apply-dev then apply-prod: each applies exactly the plan made for it.
apply-prodwaits for approval because it uses theprodenvironment.
Pull requests run the checks and plan both environments with the read-only roles and
-lock=false; the plans appear in the job summary for review, and nothing is applied. On merge to main, the plans run again and are saved astfplan-devandtfplan-prodartifacts.apply-devapplies dev, andapply-prodwaits for theprodenvironment's required reviewers before applying its saved plan.The pipeline: plans on pull requests, then apply dev, an approval gate, and apply prod on merge .github/workflows/terraform.yml name: terraform on: pull_request: paths: ["envs/**", "modules/**", ".github/workflows/terraform.yml"] push: branches: [main] paths: ["envs/**", "modules/**", ".github/workflows/terraform.yml"] permissions: contents: read # Never run two applies for the same branch at once concurrency: group: terraform-${{ github.ref }} cancel-in-progress: false env: TF_VERSION: "1.17.2" TF_IN_AUTOMATION: "true" TF_INPUT: "false" jobs: checks: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: hashicorp/setup-terraform@v3 with: terraform_version: ${{ env.TF_VERSION }} - run: terraform fmt -check -recursive - name: Module tests working-directory: modules/app-storage run: | terraform init -backend=false terraform validate terraform test plan: needs: checks runs-on: ubuntu-latest permissions: contents: read id-token: write # lets the job request an OIDC token for AWS strategy: fail-fast: false matrix: environment: [dev, prod] defaults: run: working-directory: envs/${{ matrix.environment }} steps: - uses: actions/checkout@v4 - uses: hashicorp/setup-terraform@v3 with: terraform_version: ${{ env.TF_VERSION }} terraform_wrapper: false - uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: ${{ matrix.environment == 'prod' && vars.PROD_PLAN_ROLE_ARN || vars.DEV_PLAN_ROLE_ARN }} aws-region: us-east-1 - run: terraform init - run: terraform validate # Pull requests plan without taking the state lock; main plans with it, right before apply - run: terraform plan -out=tfplan ${{ github.event_name == 'pull_request' && '-lock=false' || '' }} - name: Plan summary run: | { echo "### ${{ matrix.environment }} plan" echo '```' terraform show -no-color tfplan | tail -n 200 echo '```' } >> "$GITHUB_STEP_SUMMARY" - if: github.event_name == 'push' uses: actions/upload-artifact@v4 with: name: tfplan-${{ matrix.environment }} path: envs/${{ matrix.environment }}/tfplan retention-days: 1 # plans can contain sensitive values apply-dev: if: github.event_name == 'push' && github.ref == 'refs/heads/main' needs: plan runs-on: ubuntu-latest environment: dev permissions: contents: read id-token: write defaults: run: working-directory: envs/dev steps: - uses: actions/checkout@v4 - uses: hashicorp/setup-terraform@v3 with: terraform_version: ${{ env.TF_VERSION }} - uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: ${{ vars.DEV_APPLY_ROLE_ARN }} aws-region: us-east-1 - uses: actions/download-artifact@v4 with: name: tfplan-dev path: envs/dev - run: terraform init - run: terraform apply tfplan # exactly the reviewed plan; fails if state changed since apply-prod: needs: apply-dev runs-on: ubuntu-latest environment: prod # protection rule: required reviewers approve before this job starts permissions: contents: read id-token: write defaults: run: working-directory: envs/prod steps: - uses: actions/checkout@v4 - uses: hashicorp/setup-terraform@v3 with: terraform_version: ${{ env.TF_VERSION }} - uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: ${{ vars.PROD_APPLY_ROLE_ARN }} aws-region: us-east-1 - uses: actions/download-artifact@v4 with: name: tfplan-prod path: envs/prod - run: terraform init - run: terraform apply tfplan -
18Open a pull request
Change
noncurrent_version_daysinenvs/prod/terraform.tfvarsand open a pull request.Run git switch -c shorter-retention git commit -am "Keep old artifact versions for 60 days in prod" git push -u origin shorter-retentionCheck:On the pull request,
checksand bothplanjobs pass. The prod plan summary shows one change toaws_s3_bucket_lifecycle_configuration.artifacts(90 -> 60); dev shows no changes. -
19Merge and approve
Check:After merging,
apply-devruns on its own.apply-prodshows Waiting for review; once a reviewer approves, it applies the saved prod plan. If something changed the prod state in between, the apply stops with a stale-plan error instead of applying an outdated plan.
Clean up
Destroy with the same care you build:
- With dev credentials:
cd envs/dev && terraform destroy(the dev bucket hasforce_destroy, so it is emptied automatically). - With prod credentials: empty the prod artifacts bucket (including old versions) in the S3 console, then
cd envs/prod && terraform destroy. - In each account:
cd bootstrap/github-oidc && terraform destroywith the same-varvalues you applied with. - Remove the state buckets as shown in the remote state lab, and delete the GitHub environments and variables.
In production
The rules this repository enforces
| Rule | How |
|---|---|
| Every change is reviewed as code and as a plan | Pull requests run plan per environment and publish it in the job summary |
| What was reviewed is what gets applied | The apply job applies the saved plan file; a stale plan fails |
| Production needs a human approval | The prod GitHub environment has required reviewers; only that environment can assume the apply role |
| No long-lived credentials | GitHub OIDC tokens are exchanged for one-hour AWS sessions |
| Environments can't affect each other | Separate accounts, state buckets, roles and allowed_account_ids |
| Environments don't drift apart in code | Identical main.tf in every environment; only terraform.tfvars and backend.tf differ |
What changes as you grow
| Now | At scale |
|---|---|
| One component per environment | Several components (network, data, services), each with its own state, so plans stay small and fast |
| Module in the same repository | Shared modules in their own repository with version tags; environments pin versions and upgrade dev first |
| Plans shown in the job summary | Plan comments on the pull request, cost estimates (Infracost) and policy checks (OPA/Conftest, Checkov or Trivy) |
| Drift noticed on the next change | A scheduled plan -detailed-exitcode job alerts when reality differs from code |
Actions referenced by major version (@v4) |
Actions pinned to commit SHAs and kept current with Dependabot |
Production checklist
- One root module, state and set of credentials per environment
allowed_account_ids(or the equivalent) in every environment's provider- Modules tested in CI with
terraform test; mocked providers for speed - CI uses OIDC; no cloud keys in repository secrets
- Pull requests show the plan for every affected environment
- Applies run only from CI, use the saved plan and are serialised with
concurrency - Production applies require an approval and come from the protected
mainbranch - Plan artifacts have short retention, because they can contain sensitive values
- A documented break-glass process for when CI is down
Learn the concepts
- Terraform CI/CD and Best Practices · Terraform Tutorial
- Terraform Environments and Workspaces · Terraform Tutorial
- Terraform Modules · Terraform Tutorial
- Terraform Testing · Terraform Tutorial
- Terraform in Production · Course
- Terraform on AWS: Nonprod and Production Environments · Course
Preparing for the Terraform Associate exam? Practice tests and mock exams →