terraform-patterns
Terraform Patterns
Production-grade Terraform (and OpenTofu) patterns for writing infrastructure code that is reviewable, repeatable, and safe to apply.
When to Activate
- Writing or reviewing
.tfor.tfvarsfiles - Structuring a repo into modules and environments
- Configuring a remote backend, state locking, or state migration
- Passing variables and handling secrets in infrastructure code
- Setting up plan/apply automation in CI
- Debugging a failed plan, state drift, a lock error, or a provider version conflict
- Refactoring resources without destroying them (
moved,import)
When to Use
Same 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.
How It Works
This skill gives copy-pasteable patterns and a safe command workflow, organized by task:
- Project layout - Environments as thin roots that call reusable modules.
- Versions and providers - Pin Terraform and provider versions; commit the lock file.
- Remote state - Encrypted, locked, per-environment state.
- Variables and outputs - Typed, validated inputs and minimal outputs.
- Secrets - Keep values out of code, state exposure in mind.
- Resources -
for_eachovercount,lifecycle, and tagging. - Modules - Small, single-purpose, versioned.
- Refactoring -
movedandimportblocks instead of destroy/recreate. - Safe workflow and CI - Plan is saved, reviewed, then applied.
- Debugging and anti-patterns - Common errors and what to avoid.
Examples use AWS for concreteness. The structure applies to any provider.
Examples
| 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 |
Project Layout
Keep environments as thin root modules. Put logic in reusable modules.
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.tfvarsRules of thumb:
- One state per environment and per blast-radius boundary (network, data, apps). A single giant state makes every plan slow and every mistake large.
- Environments differ by inputs (
terraform.tfvars), not by copy-pasted resources. - Do not use workspaces as a substitute for separate production and non-production state with separate credentials.
Versions and Providers
Pin everything. Unpinned providers change behavior between runs.
# 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
}
}
}- Commit
.terraform.lock.hcl. It records provider checksums so CI and teammates install identical providers. - Do not commit the
.terraform/directory or any*.tfstatefile. - Upgrade deliberately:
terraform init -upgrade, review the lock file diff, then plan.
Remote State
Local state does not work for teams and is easy to lose. Use a remote backend with encryption and locking.
# 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)
}
}Older Terraform versions use a DynamoDB table for locking instead. Replace
use_lockfile = true with:
dynamodb_table = "example-org-tfstate-lock"Backend rules:
- Backend blocks cannot reference variables. Pass values with
-backend-configor a partial config file when you need per-environment values. - Enable bucket versioning so a bad state write can be recovered.
- Block public access on the state bucket and restrict who can read it. State often contains sensitive values.
- Never use
-lock=falseto get past a lock error. See Debugging.
Variables and Outputs
Type and validate inputs so mistakes fail at plan time.
variable "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 = []
}