Loading...
Loading...
Terraform and OpenTofu infrastructure-as-code patterns for project layout, remote state, modules, variables, secrets, safe plan/apply workflows, and CI. Use when writing or reviewing .tf files, structuring modules or environments, configuring backends and state locking, or debugging plan drift, state, and provider errors.
npx skill4agent add affaan-m/ecc terraform-patterns.tf.tfvarsmovedimportSame as When to Activate above. This alias satisfies repo skill-format conventions. Use this skill any time you are writing, reviewing, or debugging Terraform or OpenTofu configuration.
for_eachcountlifecyclemovedimport| Task | Jump to |
|---|---|
| Layout for dev/staging/prod | Project Layout |
| Remote state with locking | Remote State |
| Validated variables | Variables and Outputs |
| Avoid secrets in state and code | Secrets |
| Rename a resource without destroying it | Refactoring Without Destroying |
| Plan/apply in CI | Safe Workflow and CI |
| Lock or drift errors | Debugging |
infra/
├── modules/
│ └── network/
│ ├── main.tf
│ ├── variables.tf
│ ├── outputs.tf
│ └── versions.tf
└── envs/
├── dev/
│ ├── main.tf
│ ├── backend.tf
│ ├── providers.tf
│ └── terraform.tfvars
└── prod/
├── main.tf
├── backend.tf
├── providers.tf
└── terraform.tfvarsterraform.tfvars# versions.tf
terraform {
required_version = ">= 1.10.0, < 2.0.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.40"
}
}
}# providers.tf
provider "aws" {
region = var.region
default_tags {
tags = {
Environment = var.environment
ManagedBy = "terraform"
Owner = var.owner
}
}
}.terraform.lock.hcl.terraform/*.tfstateterraform init -upgrade# backend.tf
terraform {
backend "s3" {
bucket = "example-org-tfstate-prod"
key = "network/terraform.tfstate"
region = "us-east-1"
encrypt = true
use_lockfile = true # S3-native locking (Terraform >= 1.10)
}
}use_lockfile = truedynamodb_table = "example-org-tfstate-lock"-backend-config-lock=falsevariable "environment" {
type = string
description = "Deployment environment."
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "environment must be one of: dev, staging, prod."
}
}
variable "instance_count" {
type = number
description = "Number of application instances."
default = 2
validation {
condition = var.instance_count >= 1 && var.instance_count <= 20
error_message = "instance_count must be between 1 and 20."
}
}
variable "allowed_cidrs" {
type = list(string)
description = "CIDR blocks allowed to reach the service."
default = []
}output "vpc_id" {
description = "ID of the VPC."
value = aws_vpc.this.id
}
output "db_password" {
description = "Generated database password."
value = random_password.db.result
sensitive = true
}descriptiondefaultsensitive = true.tf.tfvarsTF_VAR_*# Read an existing secret instead of defining its value in code
data "aws_secretsmanager_secret_version" "db" {
secret_id = "prod/app/db-password"
}
resource "aws_db_instance" "app" {
identifier = "app-${var.environment}"
# ...
password = data.aws_secretsmanager_secret_version.db.secret_string
}Reading a secret through a data source still places the value in state. Treat the state file as sensitive in every case.
providerterraform.tfvars.gitignoreterraform output -jsonfor_eachcountcount# Fragile: removing "b" shifts "c" into b's slot and destroys the last index
resource "aws_iam_user" "bad" {
count = length(var.users)
name = var.users[count.index]
}
# Stable: each resource is keyed by its name; removing "b" destroys only "b"
resource "aws_iam_user" "good" {
for_each = toset(var.users)
name = each.key
}countresource "aws_cloudwatch_log_group" "app" {
count = var.enable_logging ? 1 : 0
name = "/app/${var.environment}"
}resource "aws_s3_bucket" "data" {
bucket = "example-org-data-${var.environment}"
lifecycle {
prevent_destroy = true
}
}
resource "aws_launch_template" "app" {
# ...
lifecycle {
create_before_destroy = true
}
}prevent_destroyprevent_destroyremovedremoved {
from = aws_s3_bucket.data
lifecycle {
destroy = false
}
}ignore_changesresource "aws_s3_bucket_public_access_block" "data" {
bucket = aws_s3_bucket.data.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}0.0.0.0/0module "network" {
source = "../../modules/network"
environment = var.environment
cidr_block = "10.20.0.0/16"
}
# Registry or git modules: pin a version or ref
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 5.0"
}version?ref=<tag>providerrequired_providers# Resource renamed in code: keep the existing object
moved {
from = aws_instance.web
to = aws_instance.app
}
# Adopt an existing resource into state (Terraform >= 1.5)
import {
to = aws_s3_bucket.legacy
id = "example-org-legacy-bucket"
}movedterraform stateterraform fmt -recursive
terraform init
terraform validate
terraform plan -out=tfplan
terraform show tfplan # review before applying
# STOP: get explicit human approval of the reviewed plan before the next command
terraform apply tfplan # applies exactly what was reviewedterraform applyterraform destroy-outterraform apply-/+-# .github/workflows/terraform.yml (shape only)
name: terraform
on:
pull_request:
paths: ["infra/**"]
permissions:
id-token: write # OIDC to the cloud provider, no stored keys
contents: read
pull-requests: write
jobs:
plan:
runs-on: ubuntu-latest
steps:
# Pin third-party actions to full commit SHAs, not movable tags
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: hashicorp/setup-terraform@dfe3c3f87815947d99a8997f908cb6525fc44e9e # v4.0.1
with:
terraform_version: 1.10.5 # must satisfy required_version and use_lockfile (>= 1.10)
- run: terraform fmt -check -recursive
working-directory: infra/envs/dev
- run: terraform init -input=false
working-directory: infra/envs/dev
- run: terraform validate
working-directory: infra/envs/dev
- run: terraform plan -input=false -out=tfplan
working-directory: infra/envs/devplanapply-input=falsetflintcheckovtrivy config| Symptom | Likely cause | What to do |
|---|---|---|
| Another run holds the lock, or a run crashed | Confirm no run is active, then |
| Plan shows changes you did not make | Drift, a provider upgrade, or a changed default | |
| Provider bug or version mismatch | Pin and upgrade the provider; check its issue tracker. |
| Two resources depend on each other | Break the loop with an intermediate resource or remove the redundant reference. |
| Resource already exists | It was created outside Terraform | Add an |
| Keys come from an attribute known only after apply | Key by a static value, or apply in two steps with |
| Destroy and recreate on rename | Missing | Add a |
terraform state list # what is tracked
terraform state show aws_instance.app # inspect one resource
terraform plan -refresh-only # detect drift without proposing changes
terraform providers # which providers and versions are in use
TF_LOG=DEBUG terraform plan 2> debug.log # verbose logs; may contain secretsoutput can contain credentials. Do not paste it into issues or CI logs without scrubbing it.TF_LOG
| Anti-pattern | Why it hurts | Instead |
|---|---|---|
| Applies something other than what was reviewed | |
| Removes the last safety check | Reserve it for pipelines that apply a reviewed plan |
| Local state for shared infrastructure | Lost state, no locking | Remote backend with locking |
| One huge state for everything | Slow plans, large blast radius | Split by environment and domain |
Secrets in | Leaked credentials | Runtime variables or a secret manager |
| Unpinned providers or modules | Surprise changes between runs | Version constraints plus the lock file |
| Index shift causes destroys | |
| Skips dependencies, leaves state inconsistent | Fix the root cause; use only as a one-time exception |
| Editing state by hand | Corrupts state | |
| Disabling locking to bypass a stuck lock | Concurrent writes corrupt state | Verify and |
terraform fmt -recursiveterraform validate.terraform.lock.hcl.tfvarssensitiveprevent_destroyremoveddestroy = falsemovedimportkubernetes-patternsdocker-patternsdeployment-patternssecurity-reviewdatabase-migrations