<!--
Source: https://opentofu.org/docs/ · https://developer.hashicorp.com/terraform · https://www.checkov.io/ · https://www.infracost.io/
Authored: June 2026 for the devops-engineer agent bundle.
-->
Terraform / OpenTofu IaC
Author and operate HCL infrastructure-as-code using OpenTofu 1.8+ (the 2026
default — Linux Foundation fork of Terraform, drop-in compatible) or
HashiCorp Terraform 1.9+. Includes module layout, remote state with
encryption + locking, tflint + checkov + infracost in CI, and Atlantis
for PR-driven plan/apply.
When to use
- Provisioning cloud infra (AWS, GCP, Azure, Cloudflare, Datadog, GitHub).
- Authoring a reusable module (
aws-vpc,gke-cluster). - Reviewing an IaC PR — plan diff, cost diff, policy violations.
- "We have drift — what changed in the cloud since last apply?"
- Migrating from Terraform 1.5 → OpenTofu 1.8 post-BSL relicense.
Skip when: the workload is K8s manifests (use Helm/Kustomize); a
programming-language IaC is preferred (use pulumi-iac-python-typescript);
AWS-only serverless (use aws-cdk-sst-serverless).
Setup
# OpenTofu (Linux Foundation fork — 2026 default; MPL-2.0 licensed)
brew install opentofu # macOS
# OR: snap install --classic opentofu
# OR: curl -fsSL https://get.opentofu.org/install-opentofu.sh | bash
# Terraform 1.9 (HashiCorp — BSL-licensed since 2023)
brew install terraform
# Linters + scanners + cost
brew install tflint
pip install checkov # or: brew install checkov
brew install infracost
brew install terragrunt # optional, declining vs. native modules
brew install tfsec # alt to checkov; less actively maintained
brew install terraform-docs
# tfenv / tofuenv — version managers
brew install tofuenv tfenv
Auth (cloud creds):
# AWS — use OIDC from CI; locally use SSO
aws sso login --profile prod
export AWS_PROFILE=prod
# GCP
gcloud auth application-default login
# Azure
az login
Backend creds (S3): AWS_PROFILE or AWS_ROLE_ARN via OIDC.
Common recipes
Recipe 1 — Canonical module layout
modules/aws-vpc/
├── main.tf
├── variables.tf
├── outputs.tf
├── versions.tf
└── README.md # auto-generated by terraform-docs
# versions.tf
terraform {
required_version = ">= 1.6"
required_providers {
aws = { source = "hashicorp/aws", version = "~> 5.60" }
}
}
# variables.tf
variable "cidr_block" {
description = "VPC CIDR (RFC 1918)."
type = string
validation {
condition = can(cidrnetmask(var.cidr_block))
error_message = "Must be a valid CIDR block."
}
}
# main.tf
resource "aws_vpc" "this" {
cidr_block = var.cidr_block
enable_dns_hostnames = true
tags = { Name = var.name, ManagedBy = "opentofu" }
}
# outputs.tf
output "vpc_id" { value = aws_vpc.this.id }
output "cidr" { value = aws_vpc.this.cidr_block }
terraform-docs markdown table . --output-file README.md
Recipe 2 — Remote backend with locking + encryption (AWS S3)
terraform {
backend "s3" {
bucket = "myorg-tfstate"
key = "prod/networking.tfstate"
region = "us-east-1"
dynamodb_table = "myorg-tfstate-lock"
encrypt = true
kms_key_id = "arn:aws:kms:us-east-1:123456789012:key/abcd-1234"
}
}
Bootstrap the backend itself (chicken-and-egg) in a separate bootstrap/
stack with backend "local", then migrate state once.
Recipe 3 — Standard plan/apply flow
tofu init -backend-config=backend.tfvars -reconfigure
tofu fmt -recursive
tofu validate
tflint --recursive
checkov -d . --framework terraform --skip-check CKV_AWS_18 # noisy ones
infracost diff --path . --format table
tofu plan -out=tfplan -var-file=prod.tfvars
tofu show -json tfplan | jq '.resource_changes[] | {address, change: .change.actions}'
tofu apply tfplan # NEVER `tofu apply` without a saved plan in prod
Recipe 4 — Workspaces vs separate state files
Avoid terraform workspace for env separation in prod-grade setups
— it's a single backend bucket with key prefixes; blast radius too wide.
Use separate state files per env:
# stacks/networking/prod/backend.tfvars
bucket = "myorg-tfstate"
key = "prod/networking.tfstate"
region = "us-east-1"
dynamodb_table = "myorg-tfstate-lock"
# stacks/networking/staging/backend.tfvars
bucket = "myorg-tfstate"
key = "staging/networking.tfstate"
region = "us-east-1"
dynamodb_table = "myorg-tfstate-lock"
cd stacks/networking/prod && tofu init -backend-config=../backend.tfvars
Recipe 5 — Module composition with versioning
module "vpc" {
source = "git::https://github.com/myorg/terraform-modules.git//aws-vpc?ref=v1.4.0"
cidr_block = "10.0.0.0/16"
name = "prod"
}
module "eks" {
source = "terraform-aws-modules/eks/aws"
version = "20.24.0"
cluster_name = "prod"
cluster_version = "1.30"
vpc_id = module.vpc.vpc_id
}
Pin module versions; never use ref=main.
Recipe 6 — Sensitive variables + secret outputs
variable "db_password" {
type = string
sensitive = true
}
output "db_endpoint" {
value = aws_db_instance.this.endpoint
sensitive = false
}
output "db_password_arn" {
value = aws_secretsmanager_secret.this.arn
sensitive = true
}
tofu plan masks sensitive values; tofu output db_password requires
-raw flag.
Recipe 7 — Drift detection (scheduled)
tofu plan -detailed-exitcode -lock=false -out=drift.tfplan
# exit code 0 = no diff, 2 = diff present, 1 = error
if [ $? -eq 2 ]; then
tofu show drift.tfplan > drift.txt
gh issue create --title "[drift] $(date +%F) — prod networking" --body-file drift.txt --label drift
fi
Run nightly in CI to catch out-of-band changes.
Recipe 8 — Import existing resources
# OpenTofu 1.5+ supports import blocks (declarative)
cat <<'HCL' > import.tf
import {
to = aws_s3_bucket.legacy
id = "myorg-legacy-data"
}
resource "aws_s3_bucket" "legacy" {
bucket = "myorg-legacy-data"
}
HCL
tofu plan -generate-config-out=generated.tf
tofu apply
Recipe 9 — State surgery (move, rm, replace)
tofu state list | grep aws_iam_role.api # locate
tofu state mv aws_iam_role.api module.api.aws_iam_role.this
tofu state rm aws_s3_bucket.deleted_outside
tofu apply -replace=aws_instance.web # taint + replace in one
Recipe 10 — `checkov` baseline + suppressions
checkov -d . --framework terraform --download-external-modules true --quiet
# Skip individual checks per resource (PR review will catch noise)
resource "aws_s3_bucket" "logs" {
bucket = "myorg-logs"
# checkov:skip=CKV_AWS_18: access logs not needed for log bucket itself
}
Recipe 11 — `infracost` PR comment
infracost breakdown --path . --format json --out-file infracost-base.json
git checkout pr-branch
infracost diff --path . --compare-to infracost-base.json \
--format github-comment --out-file pr-comment.md
gh pr comment --body-file pr-comment.md
In GitHub Actions, use infracost/actions/comment@v3.
Recipe 12 — Atlantis PR workflow
# atlantis.yaml
version: 3
projects:
- dir: stacks/networking/prod
autoplan:
when_modified: ["*.tf", "*.tfvars"]
enabled: true
apply_requirements: [approved, mergeable]
workflow: prod
workflows:
prod:
plan:
steps:
- init
- plan
- run: infracost diff --path . --format github-comment
apply:
steps: [apply]
Atlantis comments tofu plan on PR open; atlantis apply after approval
merges and applies.
Recipe 13 — Provider config for Cloudflare + AWS + GitHub
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 5.60" }
cloudflare = { source = "cloudflare/cloudflare", version = "~> 4.40" }
github = { source = "integrations/github", version = "~> 6.2" }
}
}
provider "aws" { region = "us-east-1" }
provider "cloudflare" { api_token = var.cloudflare_api_token }
provider "github" { owner = "myorg" }
Examples
Example 1 — New VPC + EKS module, ship via PR
Goal: Provision staging VPC + EKS in us-east-1.
mkdir -p stacks/cluster/staging && cd stacks/cluster/staging.- Author
main.tfusing community modules (Recipe 5). tofu fmt && tofu validate && tflint && checkov -d ..infracost breakdown --path .— estimated ~$320/mo.tofu plan -out=tfplan && tofu show tfplan | head -50.- PR to
infrarepo; Atlantis comments plan + cost; reviewer approves. atlantis applyfrom PR comment; state lock acquired in DynamoDB; apply succeeds.
Result: Staging EKS cluster up; state in S3; cost comment on PR.
Example 2 — Migrate from Terraform 1.5 to OpenTofu 1.8
Goal: Drop HashiCorp BSL license dep.
cd $stack && terraform state pull > state.json(backup).brew uninstall terraform && brew install opentofu.tofu init -reconfigure— OpenTofu reads same.tffiles + S3 backend.tofu plan— expect "No changes" (drop-in compat).- Update CI: replace
hashicorp/setup-terraform@v3withopentofu/setup-opentofu@v1. - Update
versions.tfif you usedrequired_version = ">= 1.5"— keep, OpenTofu honors it.
Result: Same state, same plan output; license risk gone.
Edge cases / gotchas
for_eachwith computed values (e.g., from another resource) errors
at plan time — use depends_on + terraform_data or split into two
applies.
countvsfor_each:countreindexes when an item is removed
(causes destroy/recreate); for_each uses keys. Default to for_each.
- State locking via DynamoDB requires the table to exist before
tofu init. Bootstrap separately.
- Backend changes require
init -reconfigureorinit -migrate-state.
init alone will error.
sensitive = trueon a variable hides the value from CLI output but
does NOT encrypt in state. State is plaintext; always encrypt = true
in the backend and a remote KMS key.
destroyremoves everything in the state file. Always `tofu plan
-destroy -out=tfplan and review before tofu apply tfplan`.
- Importing into a module:
import { to = module.foo.aws_s3.this, id = "..." },
not module.foo.aws_s3.this.id.
terraform_remote_statedata source ties stacks together but creates
hidden coupling — prefer SSM Parameter Store / outputs-as-secrets for
cross-stack references.
- OpenTofu encrypted state (1.7+): native state encryption — no need
for S3 KMS if you trust the OpenTofu cipher. tofu init reads the
encryption block in HCL.
tflintrules per provider — installtflint-ruleset-awsetc.
tflint --init.
- Drift between
provisioner "local-exec"and graph: provisioners
break graph correctness; use a null_resource with triggers or move
to an external tool.
Sources
- https://opentofu.org/docs/ — OpenTofu docs
- https://developer.hashicorp.com/terraform/language — Terraform language reference
- https://developer.hashicorp.com/terraform/language/modules — module structure
- https://www.checkov.io/ — Checkov IaC scanner
- https://github.com/aquasecurity/tfsec — tfsec
- https://www.infracost.io/docs/ — Infracost
- https://github.com/terraform-linters/tflint — tflint
- https://github.com/terraform-docs/terraform-docs — terraform-docs
- https://www.runatlantis.io/docs/ — Atlantis
- https://opentofu.org/blog/opentofu-1-8-0/ — OpenTofu 1.8 release notes