Terraform infrastructure as code best practices
Comprehensive Terraform and OpenTofu guidance covering testing, modules, CI/CD, and production patterns. Based on terraform-best-practices.com and enterprise experience.
Read the detailed guide before executing this skill. It retains the complete procedure and reference material. Treat its safety, prerequisites, and validation requirements as mandatory. For focused work, load the relevant sections; for end-to-end work, read the guide completely.
Activate this skill when:
Don't use this skill for:
| Scenario | Use | Why |
|---|---|---|
| Boolean condition (create or don't) | count = condition ? 1 : 0 |
Simple on/off toggle |
| Simple numeric replication | count = 3 |
Fixed number of identical resources |
| Items may be reordered/removed | for_each = toset(list) |
Stable resource addresses |
| Reference by key | for_each = map |
Named access to resources |
| Multiple named resources | for_each |
Better maintainability |
Boolean conditions:
# ā
GOOD - Boolean condition
resource "aws_nat_gateway" "this" {
count = var.create_nat_gateway ? 1 : 0
# ...
}
Stable addressing with for_each:
# ā
GOOD - Removing "us-east-1b" only affects that subnet
resource "aws_subnet" "private" {
for_each = toset(var.availability_zones)
availability_zone = each.key
# ...
}
# ā BAD - Removing middle AZ recreates all subsequent subnets
resource "aws_subnet" "private" {
count = length(var.availability_zones)
availability_zone = var.availability_zones[count.index]
# ...
}
For migration guides and detailed examples, see: Code Patterns: Count vs For_Each
# Static security scanning
trivy config .
checkov -d .
ā Don't:
ā Do:
For detailed security guidance, see: