
Terraform Skill
- 4.6k installs
- 2.2k repo stars
- Updated July 3, 2026
- antonbabenko/terraform-skill
terraform-skill is an agent skill for write, review, and debug terraform or opentofu modules, tests, ci scans, and state operations.
About
The terraform-skill skill Use when writing, reviewing, or debugging Terraform/OpenTofu modules, tests, CI, scans, or state ops - diagnoses failure mode (identity churn, secrets, blast radius, CI drift, state corruption) with version-aware guards. Diagnose-first guidance for Terraform and OpenTofu. Core file is a workflow; depth lives in references loaded on demand. Every Terraform/OpenTofu response must include: 1. Assumptions & version floor runtime (terraform or tofu), exact version, providers, state backend, execution path (local/CI/Cloud/Atlantis), environment criticality. State assumptions explicitly if the user did not provide them. 2. Risk category addressed one or more of: identity churn, secret exposure, blast radius, CI drift, compliance gaps, state corruption, provider upgrade risk, testing blind spots. 3. Chosen remediation & tradeoffs what was chosen, what was traded off, why. 4. Validation plan exact commands (fmt -check, validate, plan -out, policy check) tailored to runtime and risk tier. 5. Rollback notes for any destructive or state-mutating change: how
- Chosen remediation & tradeoffs — what was chosen, what was traded off, why.
- Validation plan — exact commands (fmt -check, validate, plan -out, policy check) tailored to runtime and risk tier.
- Rollback notes — for any destructive or state-mutating change: how to undo, what evidence to keep.
- Capture execution context — runtime+version, provider(s), backend, execution path, environment criticality.
- Diagnose failure mode(s) using the routing table below. If intent spans categories, load both references.
Terraform Skill by the numbers
- 4,577 all-time installs (skills.sh)
- +345 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #121 of 1,039 Cloud & Infrastructure skills by installs in the Skillselion catalog
- Security screen: HIGH risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
terraform-skill capabilities & compatibility
- Capabilities
- chosen remediation & tradeoffs — what was chosen · validation plan — exact commands (fmt check, va · rollback notes — for any destructive or state mu · capture execution context — runtime+version, pro · diagnose failure mode(s) using the routing table
- Use cases
- devops · ci cd
What terraform-skill says it does
Diagnose-first guidance for Terraform and OpenTofu. Core file is a workflow; depth lives in references loaded on demand.
Every Terraform/OpenTofu response must include:
2. **Risk category addressed** — one or more of: identity churn, secret exposure, blast radius, CI drift, compliance gaps, state corruption, provider upgrade risk, testing blind spots.
npx skills add https://github.com/antonbabenko/terraform-skill --skill terraform-skillAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 4.6k |
|---|---|
| repo stars | ★ 2.2k |
| Security audit | 1 / 3 scanners passed |
| Last updated | July 3, 2026 |
| Repository | antonbabenko/terraform-skill ↗ |
How do I write, review, and debug terraform or opentofu modules, tests, ci scans, and state operations with documented agent guidance?
Write, review, and debug Terraform or OpenTofu modules, tests, CI scans, and state operations.
Who is it for?
Developers who need cloud & infrastructure help during build work.
Skip if: Skip when the task falls outside Cloud & Infrastructure scope described in SKILL.md.
When should I use this skill?
Write, review, and debug Terraform or OpenTofu modules, tests, CI scans, and state operations.
What you get
Completed cloud & infrastructure workflow aligned with SKILL.md steps and validation.
- failure-mode diagnosis
- version assumption block
- module or CI review notes
By the numbers
- Chosen remediation & tradeoffs — what was chosen, what was traded off, why.
- Validation plan — exact commands (fmt -check, validate, plan -out, policy check) tailored to runtime and risk tier.
- Rollback notes — for any destructive or state-mutating change: how to undo, what evidence to keep.
Files
Terraform Skill for Claude
Diagnose-first guidance for Terraform and OpenTofu. Core file is a workflow; depth lives in references loaded on demand.
Response Contract
Every Terraform/OpenTofu response must include:
1. Assumptions & version floor — runtime (terraform or tofu), exact version, providers, state backend, execution path (local/CI/Cloud/Atlantis), environment criticality. State assumptions explicitly if the user did not provide them. 2. Risk category addressed — one or more of: identity churn, secret exposure, blast radius, CI drift, compliance gaps, state corruption, provider upgrade risk, testing blind spots. 3. Chosen remediation & tradeoffs — what was chosen, what was traded off, why. 4. Validation plan — exact commands (fmt -check, validate, plan -out, policy check) tailored to runtime and risk tier. 5. Rollback notes — for any destructive or state-mutating change: how to undo, what evidence to keep.
Never recommend direct production apply without a reviewed plan artifact and approval.
Never run terraform destroy (targeted or full) without first running terraform plan -destroy and showing the user every resource that will be deleted — including implicit dependents pulled in via locals or for_each. Get explicit confirmation before proceeding. Never use -auto-approve on destroy.
Workflow
1. Capture execution context — runtime+version, provider(s), backend, execution path, environment criticality. 2. Diagnose failure mode(s) using the routing table below. If intent spans categories, load both references. 3. Load only the matching reference file(s) — do not preload depth the task does not need. 4. Propose fix with risk controls — why this addresses the mode, what could still go wrong, guardrails (tests/approvals/rollback). 5. Generate artifacts — HCL, migration blocks (moved, import), CI changes, policy rules. 6. Validate before finalizing — run validation commands tailored to risk tier. 7. Emit the Response Contract at the end.
Diagnose Before You Generate
| Failure category | Symptoms | Primary references |
|---|---|---|
| Identity churn | Resource addresses shift after refactor, count index churn, missing moved blocks | Code Patterns: count vs for_each, Code Patterns: moved blocks, Code Patterns: LLM mistakes |
| Secret exposure | Secrets in defaults, state, logs, CI artifacts | Security & Compliance, Code Patterns: write-only, State Management |
| Blast radius | Oversized stacks, shared prod/non-prod state, unsafe applies | State Management, Module Patterns |
| Destroy cascade | Targeted destroy deletes more than expected; locals referencing a targeted resource make all for_each consumers implicit dependents | Response Contract: plan-destroy first; State Management: Safe Destroy |
| CI drift | Local plan ≠ CI plan, apply without reviewed artifact, unpinned versions | CI/CD Workflows, Code Patterns: versions |
| Compliance gaps | Missing policy stage, no approval model, no evidence retention | Security & Compliance, CI/CD Workflows |
| Testing blind spots | Plan-only validation of computed values, set-type indexing, mock/real confusion | Testing Frameworks |
| State corruption / recovery | Stuck lock, backend migration, drift reconciliation | State Management |
| Provider upgrade risk | Breaking-change provider bump, unpinned modules | Code Patterns: versions, Module Patterns |
| Provider lifecycle | Removing a provider with resources still in state, orphaned resources, removed block usage | State Management: Provider Removal |
| Bootstrap / orchestration misuse | null_resource + local-exec for bootstrap, remote-exec for setup scripts, provisioner stdout leaking secrets in CI logs | Code Patterns: Provisioners as Last Resort |
| Navigation / safe-rename blind spots | Cannot locate symbol defs/refs semantically, value-symbol rename done as blind text replace, grep-only refactor missing refs, hallucinated rg shim | Code Intelligence |
| Cross-cloud / provider mapping | "What's the Azure/GCP equivalent of X", picking a backend/auth model per cloud | State Management: Cross-cloud equivalents |
When to Use This Skill
Activate when: creating or reviewing Terraform/OpenTofu configurations or modules, setting up or debugging tests, structuring multi-environment deployments, implementing IaC CI/CD, choosing module patterns or state organization, configuring or migrating remote state backends.
Don't use for: basic HCL syntax questions Claude already knows, provider API reference (link to docs), cloud-platform questions unrelated to Terraform/OpenTofu.
Core Principles
Module Hierarchy
| Type | When to Use | Scope |
|---|---|---|
| Resource module | Single logical group of connected resources | VPC + subnets, SG + rules |
| Infrastructure module | Collection of resource modules for a purpose | Multiple resource modules in one region/account |
| Composition | Complete infrastructure | Spans multiple regions/accounts |
Flow: resource → resource module → infrastructure module → composition.
Directory Layout
environments/ # prod/ staging/ dev/ — per-env configurations
modules/ # networking/ compute/ data/ — reusable modules
examples/ # minimal/ complete/ — docs + integration fixturesSeparate environments from modules. Use examples/ as both documentation and test fixtures. Keep modules small and single-responsibility.
See Module Patterns for architecture principles, naming conventions, variable/output contracts.
Naming Conventions (summary)
- Descriptive resource names (
aws_instance.web_server, notaws_instance.main) - Reserve
thisfor genuine singleton resources only - Prefix variables with context (
vpc_cidr_block, notcidr) - Standard files:
main.tf,variables.tf,outputs.tf,versions.tf
See Module Patterns: Variable Naming and Code Patterns: Block Ordering for examples.
Block Ordering (summary)
Resource blocks: count/for_each first → arguments → tags → depends_on → lifecycle. Variable blocks: description → type → default → validation → nullable → sensitive.
See Code Patterns: Block Ordering & Structure for the full rules and examples.
Testing Strategy
Decision Matrix: Which Testing Approach?
| Situation | Approach | Tools | Cost |
|---|---|---|---|
| Quick syntax check | Static analysis | validate, fmt | Free |
| Pre-commit validation | Static + lint | validate, tflint, trivy, checkov | Free |
| Terraform 1.6+, simple logic | Native test framework | terraform test | Free-Low |
| Pre-1.6, or Go expertise | Integration testing | Terratest | Low-Med |
| Security/compliance focus | Policy as code | OPA, Sentinel | Free |
| Cost-sensitive workflow | Mock providers (1.7+) | Native tests + mocks | Free |
| Multi-cloud, complex | Full integration | Terratest + real infra | Med-High |
Native Test Rules (1.6+)
Before writing test code: validate resource schemas via Terraform MCP so assertions target real attributes.
command = plan— fast, for input-derived values onlycommand = apply— required for computed values (ARNs, generated names) and set-type nested blocks- Set-type blocks cannot be indexed with
[0]— useforexpressions or materialize viacommand = apply - Common set types: S3 encryption rules, lifecycle transitions, IAM policy statements
See Testing Frameworks for static-analysis pipelines, native-test patterns, Terratest integration, mock providers, and the full LLM-mistake checklist.
Count vs For_Each — Quick Rule
| Scenario | Use | Why |
|---|---|---|
| Boolean condition (create / don't) | count = condition ? 1 : 0 | Optional singleton toggle |
| Items may be reordered or removed | for_each = toset(list) | Stable resource addresses |
| Reference by key | for_each = map | Named access |
| Multiple named resources | for_each | Better identity stability |
Never use list index as long-lived identity — removing a middle element reshuffles every address after it. For the decision matrix, safe migration playbook, moved block patterns, and known-at-plan failure cases, see Code Patterns: count vs for_each.
Locals for Dependency Management
Using try() in a local to prefer a conditional resource's attribute over its parent is a specialized but high-value pattern — it forces correct deletion order without explicit depends_on. Common use: VPC + secondary CIDR associations + subnets.
See Code Patterns: Locals for Dependency Management for the full pattern and worked example.
Module Development
Standard layout:
my-module/
├── README.md # Usage documentation
├── main.tf # Primary resources
├── variables.tf # Typed inputs with descriptions
├── outputs.tf # Output values
├── versions.tf # required_version + required_providers
├── examples/
│ ├── minimal/
│ └── complete/
└── tests/
└── module_test.tftest.hcl # or Go for TerratestVariable contracts: always description, always explicit type, use validation for complex constraints, use sensitive = true for secrets, prefer optional() with typed defaults (1.3+) over untyped map(any).
Output contracts: always description, mark sensitive outputs, expose stable subsets (not whole provider objects).
See Module Patterns for the full contract patterns, module release checklist, and LLM-mistake checklist.
CI/CD
Pipeline stages: validate → test → plan → apply (with environment protection).
Cost control: mock providers on PR validation, real-cloud integration only on main or scheduled, tag test resources, auto-cleanup.
Drift prevention: pin runtime and providers, commit .terraform.lock.hcl, apply the reviewed plan artifact from the plan stage (do not re-run plan inside the apply job), run policy/security stage on every path to apply.
See CI/CD Workflows for GitHub Actions, GitLab CI, and Atlantis templates plus the LLM-mistake checklist.
Security & Compliance
Essential checks:
trivy config .
checkov -d .Don't: store secrets in variables or .tfvars, use default VPC, skip encryption, open security groups to 0.0.0.0/0, use inline ingress/egress blocks in aws_security_group.
Do: source secrets from a cloud secret manager (AWS Secrets Manager / Azure Key Vault / GCP Secret Manager) or use write_only arguments on 1.11+, create dedicated VPCs, enforce encryption at rest and TLS, least-privilege SGs, use separate aws_vpc_security_group_{ingress,egress}_rule resources (e.g. AWS provider v5+).
Marking a variable sensitive = true masks display only — the value still lives in state. Use write_only / *_wo on 1.11+, or keep secret material out of Terraform entirely via runtime lookups.
See Security & Compliance for trivy/checkov pipelines, state-file hardening, compliance mappings, and the LLM-mistake checklist.
State Management
Never use local state in teams or production. Remote backends provide automatic locking, encryption, versioning, audit logging, and safe collaboration.
Choosing a Remote Backend
AWS example (Azure azurerm / GCP gcs / TF Cloud syntax: see State Management: Choosing a Remote Backend):
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/vpc/terraform.tfstate"
region = "us-east-1"
encrypt = true
use_lockfile = true # Native S3 locking, 1.10+
}
}On Terraform < 1.10, use dynamodb_table = "terraform-state-lock" instead of use_lockfile. Azure Storage, GCS, and Terraform Cloud all offer built-in locking - see the State Management reference for syntax. For choosing among backends and their locking models, see Choosing a Remote Backend.
State Organization
| Pattern | Use When | Example Path |
|---|---|---|
| Per environment | Different teams per env | prod/terraform.tfstate, staging/... |
| Per component | Independent lifecycles | prod/vpc/, prod/eks/, prod/rds/ |
| Hybrid (recommended) | Both benefits | prod/networking/, prod/compute/, staging/networking/ |
Split state when: different teams, different update cadences, or >500 resources. Combine when: tightly coupled resources, <100 resources, same lifecycle.
See State Management for locking, migration, multi-team isolation, disaster recovery, and the LLM-mistake checklist.
Version Management
| Component | Strategy | Example |
|---|---|---|
| Terraform runtime | Pin minor | required_version = "~> 1.9" |
| Providers | Pin major | version = "~> 5.0" |
| Modules (prod) | Pin exact | version = "5.1.2" |
| Modules (dev) | Allow patch | version = "~> 5.1" |
Commit .terraform.lock.hcl intentionally. Keep provider/runtime upgrades in a separate PR from functional changes. See Code Patterns: Version Management for constraint syntax and upgrade workflow.
Modern Terraform Features (1.0+)
| Feature | Min version | Common use |
|---|---|---|
try() | 0.13+ | Safe fallbacks, replaces element(concat()) |
nullable = false | 1.1+ | Prevent null silently overriding defaults |
moved blocks | 1.1+ | Refactor without destroy/recreate |
optional() with defaults | 1.3+ | Typed object attributes |
import blocks | 1.5+ | Declarative imports, reviewable in VCS |
check blocks | 1.5+ | Runtime assertions |
Native terraform test | 1.6+ | Built-in test framework |
| Mock providers | 1.7+ | Cost-free unit testing |
removed blocks | 1.7+ | Declarative resource removal |
| Provider-defined functions | 1.8+ | Provider-specific transformations (requires provider to declare functions) |
| Cross-variable validation | 1.9+ | Reference other var.* in validation blocks |
write_only arguments | 1.11+ | Secrets never stored in state |
| S3 native lock-file | 1.10+ | State locking without DynamoDB |
Before emitting a feature, verify the runtime floor. See Code Patterns: Feature Guard Table for the full table with common LLM error patterns per feature.
Runtime-Specific Guidance
- Terraform 1.0-1.5 (OpenTofu starts at 1.6): Terratest for integration, static analysis + plan validation only (no native tests).
- 1.6+: native
terraform test/tofu testavailable — migrate simple unit tests, keep Terratest for complex integration. - 1.7+: mock providers cut test cost — mock for unit tests, real runs for final integration.
- 1.10+: S3 native lock-file (
use_lockfile) is the correct default for new configurations — DynamoDB locking is no longer required. - 1.11+:
write_onlyarguments for secret handling keep credentials out of state. - Terraform vs OpenTofu: both supported. For licensing, governance, and feature delta, see Quick Reference: Terraform vs OpenTofu.
Code Intelligence (terraform-ls)
Semantic navigation for HCL. terraform-ls is optional; without it every row below degrades to a disclosed rg + Read fallback.
Self-contained terraform-ls layer of a generic code-intelligence discipline - apply the rows below directly. Recommended companion: the code-intelligence plugin (same antonbabenko/agent-plugins marketplace) carries the generic discipline (position anchoring, degradation gate, disclosure format, anti-phantom-shim) and ships /code-intelligence:doctor for readiness. If it is installed, defer to its generic protocol; this skill stays fully self-contained without it.
| Goal | Use | Tradeoff |
|---|---|---|
| Find definition / all references | terraform-ls goToDefinition / findReferences | Needs init + a position anchor |
| Rename value symbol (var/local/output/provider alias) | Manual: findReferences -> per-file fresh Read -> edit -> validate | No rename provider |
| Rename resource/module address | moved block + plan shows 0 destroy | Text rename forces destroy/recreate |
Exact text / known name / .tfvars / non-HCL | rg + Read | No semantic scope |
✅ Supported: goToDefinition, findReferences, documentSymbol, hover, workspaceSymbol. ❌ Unsupported: goToImplementation, call hierarchy, rename provider. Do not call these then report their absence as a finding.
- ✅ Prereq: local
terraform/tofuon PATH,terraform initrun; cold start may need one retry. - ✅ LSP calls are position-anchored (
file:line:character) - anchor withrgfirst, never symbol-name-only. - ❌ Do not claim "LSP broken, using rg" until the Degradation Gate passes; disclose any tool substitution on the first line.
Depth: Code Intelligence.
Reference Files
Progressive disclosure — essentials here, depth on demand:
- Testing Frameworks — static analysis, native tests, Terratest, mock providers
- Module Patterns — structure, variable/output contracts,
terraform_remote_staterules, release checklist - CI/CD Workflows — GitHub Actions, GitLab CI, Atlantis, cost control
- Security & Compliance — trivy/checkov, secrets handling, compliance mappings
- State Management — backends, locking, migration, multi-team, recovery
- Code Patterns — block ordering,
count/for_eachdeep dive, modern features, version management, locals - Code Intelligence - terraform-ls capabilities, position-anchored calls, manual rename, degradation gate
- Quick Reference — command cheat sheets, flowcharts, troubleshooting
License
Apache License 2.0. See LICENSE for full terms.
Copyright © 2026 Anton Babenko
CI/CD Workflows for Terraform
Part of: terraform-skill
Purpose: CI/CD integration patterns for Terraform/OpenTofu
This document provides detailed CI/CD workflow templates and optimization strategies for infrastructure-as-code pipelines.
---
Table of Contents
1. GitHub Actions Workflow 2. GitLab CI Template 3. Cost Optimization 4. Automated Cleanup 5. Best Practices
---
GitHub Actions Workflow
Complete Example
# .github/workflows/terraform.yml
name: Terraform
on:
push:
branches: [main]
pull_request:
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- name: Terraform Format
run: terraform fmt -check -recursive
- name: Terraform Init
run: terraform init
- name: Terraform Validate
run: terraform validate
- uses: terraform-linters/setup-tflint@v4
with:
tflint_version: v0.50.3
- name: TFLint Init
run: tflint --init
- name: TFLint
run: tflint
test:
needs: validate
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- name: Run Terraform Tests
run: terraform test
# Or for Terratest:
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: 'stable'
- name: Run Terratest
run: |
cd tests
go test -v -timeout 30m -parallel 4
plan:
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- name: Terraform Init
run: terraform init
- name: Terraform Plan
run: terraform plan -out=tfplan
- name: Upload Plan
uses: actions/upload-artifact@v4
with:
name: tfplan
path: tfplan
apply:
needs: plan
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
environment: production
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- name: Download Plan
uses: actions/download-artifact@v4
with:
name: tfplan
- name: Terraform Init
run: terraform init
- name: Terraform Apply
run: terraform apply tfplanWith Cost Estimation (Infracost)
cost-estimate:
needs: plan
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Infracost
uses: infracost/actions/setup@v2
with:
api-key: ${{ secrets.INFRACOST_API_KEY }}
- name: Generate Cost Estimate
run: |
infracost breakdown --path . \
--format json \
--out-file /tmp/infracost.json
- name: Post Cost Comment
uses: infracost/actions/comment@v1
with:
path: /tmp/infracost.json
behavior: update---
GitLab CI Template
# .gitlab-ci.yml
stages:
- validate
- test
- plan
- apply
variables:
TF_ROOT: ${CI_PROJECT_DIR}
.terraform_template:
image: hashicorp/terraform:latest
before_script:
- cd ${TF_ROOT}
- terraform init
validate:
extends: .terraform_template
stage: validate
script:
- terraform fmt -check -recursive
- terraform validate
test:
extends: .terraform_template
stage: test
script:
- terraform test
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
- if: '$CI_COMMIT_BRANCH == "main"'
plan:
extends: .terraform_template
stage: plan
script:
- terraform plan -out=tfplan
artifacts:
paths:
- ${TF_ROOT}/tfplan
expire_in: 1 week
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
- if: '$CI_COMMIT_BRANCH == "main"'
apply:
extends: .terraform_template
stage: apply
script:
- terraform apply tfplan
dependencies:
- plan
rules:
- if: '$CI_COMMIT_BRANCH == "main"'
when: manual
environment:
name: production---
Cost Optimization
Strategy
1. Use mocking for PR validation (free) 2. Run integration tests only on main branch (controlled cost) 3. Implement auto-cleanup (prevent orphaned resources) 4. Tag all test resources (track spending)
Example: Conditional Test Execution
# GitHub Actions
test:
runs-on: ubuntu-latest
steps:
- name: Run Unit Tests (Mocked)
run: terraform test
- name: Run Integration Tests
if: github.ref == 'refs/heads/main'
run: |
cd tests
go test -v -timeout 30mCost-Aware Test Tags
// In Terratest
terraformOptions := &terraform.Options{
TerraformDir: "../examples/complete",
Vars: map[string]interface{}{
"tags": map[string]string{
"Environment": "test",
"CreatedAt": time.Now().Format(time.RFC3339),
"CreatedBy": "CI",
"JobID": os.Getenv("GITHUB_RUN_ID"),
},
},
}---
Automated Cleanup
Cleanup Script (Bash)
#!/bin/bash
# cleanup-test-resources.sh
# Resources are tagged with CreatedAt = ISO8601 timestamp (RFC3339).
# AWS resourcegroupstaggingapi tag filters only support equality, so we
# fetch by Environment=test and filter by timestamp client-side with jq.
set -euo pipefail
CUTOFF=$(date -u -d '2 hours ago' +%s)
aws resourcegroupstaggingapi get-resources \
--tag-filters Key=Environment,Values=test \
--query 'ResourceTagMappingList[]' \
--output json | \
jq -r --argjson cutoff "$CUTOFF" '
.[]
| select(
any(.Tags[]; .Key == "CreatedAt" and (.Value | fromdateiso8601) < $cutoff)
)
| .ResourceARN
' | while read -r arn; do
instance_id=$(echo "$arn" | grep -oP 'instance/\K[^/]+' || true)
if [ -n "$instance_id" ]; then
echo "Terminating instance: $instance_id"
aws ec2 terminate-instances --instance-ids "$instance_id"
fi
doneScheduled Cleanup (GitHub Actions)
# .github/workflows/cleanup.yml
name: Cleanup Test Resources
on:
schedule:
- cron: '0 */2 * * *' # Every 2 hours
workflow_dispatch: # Manual trigger
permissions:
id-token: write # required for OIDC role assumption
contents: read
jobs:
cleanup:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_CLEANUP_ROLE_ARN }}
aws-region: us-east-1
- name: Run Cleanup Script
run: ./scripts/cleanup-test-resources.sh---
Best Practices
1. Separate Environments
# Different workflows for different environments
.github/workflows/
terraform-dev.yml
terraform-staging.yml
terraform-prod.ymlOr use reusable workflows:
# .github/workflows/terraform-deploy.yml (reusable)
on:
workflow_call:
inputs:
environment:
required: true
type: string
jobs:
deploy:
environment: ${{ inputs.environment }}
# ... deployment steps2. Require Approvals for Production
# GitHub Actions — configure required reviewers on the `production`
# environment in repo Settings -> Environments -> Protection rules.
apply:
environment:
name: production3. Use Remote State
# backend.tf
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
use_lockfile = true # 1.10+, native S3 locking (replaces DynamoDB)
encrypt = true
}
}4. Implement State Locking
# In CI, use -lock-timeout to handle concurrent runs
- name: Terraform Apply
run: terraform apply -lock-timeout=10m tfplan5. Cache Terraform Plugins
# GitHub Actions — set TF_PLUGIN_CACHE_DIR so `terraform init` actually
# writes into the cached path, then restore the cache between runs.
jobs:
plan:
runs-on: ubuntu-latest
env:
TF_PLUGIN_CACHE_DIR: ${{ runner.temp }}/terraform-plugin-cache
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- name: Create plugin cache dir
run: mkdir -p "$TF_PLUGIN_CACHE_DIR"
- name: Cache Terraform Plugins
uses: actions/cache@v4
with:
path: ${{ runner.temp }}/terraform-plugin-cache
key: ${{ runner.os }}-terraform-${{ hashFiles('**/.terraform.lock.hcl') }}
- name: Terraform Init
run: terraform init6. Security Scanning in CI
security-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run Trivy
uses: aquasecurity/trivy-action@0.29.0
with:
scan-type: 'config'
scan-ref: '.'
- name: Run Checkov
uses: bridgecrewio/checkov-action@v12.2.0
with:
directory: .
framework: terraformOIDC Trust Policy Correctness
| Platform | Expected aud | Where to pin sub |
|---|---|---|
| GitHub Actions → AWS | sts.amazonaws.com | repo:<org>/<repo>:ref:refs/heads/<branch> |
| GitHub Actions → Azure AD | api://AzureADTokenExchange | repo:<org>/<repo>:environment:<env> |
| GitHub Actions → GCP | value passed via audience parameter | repo + ref or environment |
| GitLab CI → AWS | matches $CI_SERVER_URL | project path + ref |
Use keyless OIDC for all three clouds (AWS OIDC / Azure federated credentials / GCP Workload Identity Federation). Static keys only if OIDC is unavailable (non-OIDC CI / self-hosted runners) - prefer keyless.
Rules:
- ✅ pin
audto the exact value from the table - ✅ pin
subto a specific repo + branch or environment — no wildcards across org/repo - ❌
subwildcards likerepo:*:*orrepo:<org>/*:ref:*let any repo assume the role - ❌ mismatched
aud→ token rejected with opaque error; fixaudper table, do not relaxsub
✅ DO — AWS IAM trust-policy Condition block (the only non-boilerplate fragment):
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
},
"StringLike": {
"token.actions.githubusercontent.com:sub": "repo:my-org/my-repo:ref:refs/heads/main"
}
}Drift Detection — Alert, Do Not Auto-Apply
Scheduled drift detection alerts; it never auto-applies.
✅ DO — scheduled plan with alert on drift (exit code 2):
# .github/workflows/drift-detection.yml
on:
schedule:
- cron: '0 */6 * * *'
jobs:
detect:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- run: terraform init
- name: Plan (detect drift)
id: plan
run: terraform plan -detailed-exitcode -out=plan.bin
continue-on-error: true
- name: Alert on drift
if: steps.plan.outcome == 'failure' && steps.plan.outputs.exitcode == '2'
run: |
echo "Drift detected. Requires human review before apply."
# send to Slack / PagerDuty / issue trackerplan -detailed-exitcode exit codes: 0 = no drift, 1 = plan failed, 2 = drift detected.
❌ DON'T — scheduled auto-apply that silently reconciles drift:
jobs:
reconcile:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: terraform apply -auto-approve---
Atlantis Integration
Atlantis provides Terraform automation via pull request comments.
atlantis.yaml
version: 3
projects:
- name: production
dir: environments/prod
workspace: default
terraform_version: 1.12.0
workflow: custom
workflows:
custom:
plan:
steps:
- init
- plan:
extra_args: ["-lock=false"]
apply:
steps:
- applyBenefits
- Plan results as PR comments
- Apply via PR comments
- Locking prevents concurrent changes
- Integrates with VCS (GitHub, GitLab, Bitbucket)
---
Troubleshooting
Issue: Tests fail in CI but pass locally
Cause: Different Terraform/provider versions
Solution:
# versions.tf - Pin versions
terraform {
required_version = ">= 1.6.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}Issue: Parallel tests conflict
Cause: Resource naming collisions
Solution:
// Use unique identifiers
uniqueId := random.UniqueId()
bucketName := fmt.Sprintf("test-bucket-%s-%s",
os.Getenv("GITHUB_RUN_ID"),
uniqueId)---
LLM Mistake Checklist — CI/CD
Common model mistakes to correct before returning pipeline recommendations:
- generates a pipeline with no lockfile strategy (
.terraform.lock.hcluncommitted or unreviewed) - re-runs
terraform planinside the apply job instead of consuming the reviewed plan artifact from the plan stage - omits environment protection / approval gates on production apply
- uses unpinned provider versions, causing drift between local and CI runs
- skips the policy/security stage despite the pipeline claiming compliance
- grants CI long-lived static cloud credentials instead of OIDC / workload-identity federation
- writes OIDC trust policies with wildcard
subclaims (repo:*:*,repo:<org>/*:ref:*) — any repo or branch can assume the role - mismatches the
audclaim between CI platform and cloud provider, then relaxessubto "fix" the resulting error - implements scheduled "drift detection" as
terraform apply -auto-approveon cron — silently reverts out-of-band changes; useplan -detailed-exitcode+ alert - fails to restrict artifact access when
terraform show -jsonresults may contain sensitive plan output - merges provider/runtime upgrades with functional changes in the same PR
---
Back to: Main Skill File
Code Intelligence (terraform-ls)
Semantic navigation for HCL via the terraform-ls language server. Use the LSP for symbol relationships; use rg + Read for text. Pick by task, not by habit.
terraform-ls is optional. Without it, every operation below degrades to a disclosed rg + Read fallback (see Degradation Gate). It is not a hard dependency of this skill.
Self-contained terraform-ls specialization (capability matrix, terraform init, moved blocks, .tfvars) of a generic code-intelligence discipline - apply it directly.
Recommended companion: the code-intelligence plugin (same antonbabenko/agent-plugins marketplace) is the single source of truth for the generic discipline - tool precedence, position anchoring, the two-case degradation gate, the first-line disclosure format, anti-phantom-shim proof - and ships /code-intelligence:doctor. When it is installed, defer to its generic protocol; the Terraform-specific capability matrix, routing, rename workflow, and operational notes below remain owned here and work without it.
Security: terraform init may download modules and providers over the network. Do not auto-run it in untrusted working directories. terraform-ls indexes local source only; it does not execute the configuration.
Setup (host prerequisites)
terraform-ls is optional; everything below degrades to a disclosed rg + Read fallback without it. To get the semantic tier:
1. Install the language server:
- macOS:
brew install hashicorp/tap/terraform-ls - Any (Go):
go install github.com/hashicorp/terraform-ls@latest - Verify:
terraform-ls --version
2. Enable the agent's LSP tool. In Claude Code, export ENABLE_LSP_TOOL=1 in your shell rc and reload; LSP tools require explicit opt-in. 3. Install an LSP transport that exposes a POSITION-based terraform-ls tool (filePath, line, character). One option is the third-party terraform-ls bridge from the boostvolt/claude-code-lsps marketplace: /plugin marketplace add boostvolt/claude-code-lsps then /plugin install terraform-ls@claude-code-lsps. If the only LSP tool exposed takes a bare symbol name, the transport is wrong/old - reinstall and fully restart the agent. 4. Fully restart the agent (kill the process, not just a new session) - plugins loading without a clean restart is the most common silent failure. 5. Verify readiness. If the companion code-intelligence plugin is installed, run /code-intelligence:doctor (checks rg + language servers including terraform-ls). Otherwise verify by hand: rg --version prints ripgrep x.y.z, terraform-ls --version succeeds, and a documentSymbol call on a variables.tf returns symbols (liveness probe). An initialized workspace (terraform init run, .terraform/ present) is required for cross-module and provider resolution.
terraform-ls Capability Matrix
Anchor target for the SKILL.md diagnose row. What the server can and cannot do.
| Operation | Supported | Semantic guarantee |
|---|---|---|
goToDefinition | ✅ | Jumps usage -> declaration (var/local/output/module/resource) |
findReferences | ✅ | Enumerates references to the symbol at the given position, workspace-scoped |
documentSymbol | ✅ | Outline of one file (blocks, variables, outputs, resources, modules) |
hover | ✅ | Provider/resource attribute docs and inferred type at position |
workspaceSymbol | ✅ | Broad symbol inventory; expensive, avoid for single-name lookup |
goToImplementation | ❌ | Not implemented by terraform-ls |
prepareCallHierarchy / incomingCalls / outgoingCalls | ❌ | No call hierarchy in terraform-ls |
| rename provider | ❌ | No server-side rename; renames are manual (see below) |
- ❌ Do not call unsupported operations and report their absence as a finding.
Redirect call-hierarchy intent to findReferences.
- ✅ Treat
findReferencesas the authoritative reference set once the
Degradation Gate passes.
Position-Anchored Calls
terraform-ls resolves by source position, not by symbol name.
- ✅ Call with
file:line:characterpointing at an occurrence of the symbol. - ✅ Anchor the position first with
rg/Grep (find a known occurrence), then
issue the LSP call at that location.
- ❌ Never pass a bare symbol name and expect resolution. A name-only call
returning empty is a usage defect, not server degradation.
- ✅ Prereq: a local
terraform(ortofu) binary on PATH, and
terraform init run in the workspace, before relying on cross-module or provider resolution.
- ✅ Cold start: the first call after server launch may return empty while
indexing. Retry once before concluding anything.
Manual Rename Workflow
terraform-ls has no rename provider. Branch by what is being renamed.
(a) Value symbol - variable, local, output, or provider alias:
1. findReferences at an anchored position to enumerate every reference. 2. For EACH file with references: do a fresh Read of that file immediately before editing it. Offsets shift after a prior in-file edit; a stale view produces corrupted edits. 3. Apply the edit, then re-run terraform validate and check LSP diagnostics are clean.
(b) Resource or module address - this is NOT a text rename:
- Add a
movedblock and runterraform plan; confirm it shows 0 destroy /
0 create for the moved address.
- See Code Patterns: Moved Blocks
for block syntax and the count/for_each address rules.
❌ Never blind-replace a resource address as text - it forces destroy/recreate.
Degradation Gate
Pass ALL three before claiming "LSP unavailable, using rg instead". A vendored or uninitialized workspace can legitimately return empty.
1. documentSymbol on a file in scope returns symbols -> server is responsive. (Responsiveness only; NOT proof of complete reference coverage.) 2. The failing call was position-anchored (not symbol-name-only). 3. That anchored call still returned empty.
Only then is a disclosed rg fallback warranted. State the substitution on the first line of the response:
Intended: terraform-ls findReferences. Actual: rg. Reason: <gate result>. Impact: text matches only, no semantic scoping - may include comments/strings.
❌ Do not assert a fallback without running the gate. ❌ Do not bury the substitution at the end of the response.
When to Use rg Instead
LSP is the wrong tool for these; go straight to rg + Read:
- Exact text or a known literal string.
- Known-name lookup where you already have the file and only need the line.
.tfvarsfiles (values, not HCL symbol graph).- Comments, generated docs, READMEs, lockfiles.
- Any non-HCL file.
Code Patterns & Structure
Part of: terraform-skill
Purpose: Comprehensive patterns for Terraform/OpenTofu code structure and modern features
This document provides detailed code patterns, structure guidelines, and modern Terraform features. For high-level principles, see the main skill file.
---
Table of Contents
1. Block Ordering & Structure 2. Count vs For_Each Deep Dive 3. Modern Terraform Features (1.0+) 4. Version Management 5. Refactoring Patterns 6. Locals for Dependency Management
---
Block Ordering & Structure
Resource Block Structure
Strict argument ordering:
1. count or for_each FIRST (blank line after) 2. Other arguments (alphabetical or logical grouping) 3. tags as last real argument 4. depends_on after tags (if needed) 5. lifecycle at the very end (if needed)
# ✅ GOOD - Correct ordering
resource "aws_nat_gateway" "this" {
count = var.create_nat_gateway ? 1 : 0
allocation_id = aws_eip.this[0].id
subnet_id = aws_subnet.public[0].id
tags = {
Name = "${var.name}-nat"
Environment = var.environment
}
depends_on = [aws_internet_gateway.this]
lifecycle {
create_before_destroy = true
}
}
# ❌ BAD - Wrong ordering
resource "aws_nat_gateway" "this" {
allocation_id = aws_eip.this[0].id
tags = { Name = "nat" }
count = var.create_nat_gateway ? 1 : 0 # Should be first
subnet_id = aws_subnet.public[0].id
lifecycle {
create_before_destroy = true
}
depends_on = [aws_internet_gateway.this] # Should be after tags
}Pattern applies identically on Azure/GCP; for resource equivalents see Module Patterns: Cross-cloud resource map.
Variable Definition Structure
Variable block ordering:
1. description (ALWAYS required) 2. type 3. default 4. sensitive (when setting to true) 5. nullable (when setting to false) 6. validation
# ✅ GOOD - Correct ordering and structure
variable "environment" {
description = "Environment name for resource tagging"
type = string
default = "dev"
nullable = false
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "Environment must be one of: dev, staging, prod."
}
}Variable Type Preferences
- Prefer simple types (
string,number,list(),map()) overobject()unless strict validation needed - Use
optional()for optional object attributes (Terraform 1.3+) - Use
anyto disable validation at certain depths or support multiple types
Modern variable patterns (Terraform 1.3+):
# ✅ GOOD - Using optional() for object attributes
variable "database_config" {
description = "Database configuration with optional parameters"
type = object({
name = string
engine = string
instance_class = string
backup_retention = optional(number, 7) # Default: 7
monitoring_enabled = optional(bool, true) # Default: true
tags = optional(map(string), {}) # Default: {}
})
}
# Usage - only required fields needed
database_config = {
name = "mydb"
engine = "mysql"
instance_class = "db.t3.micro"
# Optional fields use defaults
}Complex type example:
# For lists/maps of same type
variable "subnet_configs" {
description = "Map of subnet configurations"
type = map(map(string)) # All values are maps of strings
}
# When types vary, use any
variable "mixed_config" {
description = "Configuration with varying types"
type = any
}Output Structure
Pattern: {name}_{type}_{attribute}
# ✅ GOOD
output "security_group_id" { # "this_" should be omitted
description = "The ID of the security group"
value = try(aws_security_group.this[0].id, "")
}
output "private_subnet_ids" { # Plural for list
description = "List of private subnet IDs"
value = aws_subnet.private[*].id
}
# ❌ BAD
output "this_security_group_id" { # Don't prefix with "this_"
value = aws_security_group.this[0].id
}
output "subnet_id" { # Should be plural "subnet_ids"
value = aws_subnet.private[*].id # Returns list
}---
Count vs For_Each Deep Dive
When to use count
✓ Simple numeric replication:
resource "aws_subnet" "public" {
count = 3
cidr_block = cidrsubnet(var.vpc_cidr, 8, count.index)
}✓ Boolean conditions (create or don't):
# ✅ GOOD - Boolean condition
resource "aws_nat_gateway" "this" {
count = var.create_nat_gateway ? 1 : 0
}
# Less preferred - length check
resource "aws_nat_gateway" "this" {
count = length(var.public_subnets) > 0 ? 1 : 0
}✓ When order doesn't matter and items won't change
When to use for_each
✓ Reference resources by key:
resource "aws_subnet" "private" {
for_each = toset(var.availability_zones)
vpc_id = aws_vpc.this.id
availability_zone = each.key
cidr_block = cidrsubnet(var.vpc_cidr, 4, index(var.availability_zones, each.key))
}
# Reference by key: aws_subnet.private["us-east-1a"]✓ Items may be added/removed from middle:
# ❌ BAD with count - removing middle item recreates all subsequent resources
resource "aws_subnet" "private" {
count = length(var.availability_zones)
availability_zone = var.availability_zones[count.index]
# If var.availability_zones[1] removed, all resources after recreated!
}
# ✅ GOOD with for_each - removal only affects that one resource
resource "aws_subnet" "private" {
for_each = toset(var.availability_zones)
availability_zone = each.key
# Removing one AZ only destroys that subnet
}✓ Creating multiple named resources:
variable "environments" {
default = {
dev = {
instance_type = "t3.micro"
}
prod = {
instance_type = "t3.large"
}
}
}
resource "aws_instance" "app" {
for_each = var.environments
instance_type = each.value.instance_type
tags = {
Environment = each.key # "dev" or "prod"
}
}Count to For_Each Migration
When to migrate: When you need stable resource addressing or items might be added/removed from middle of list.
Migration steps:
1. Add for_each to resource 2. Use moved blocks to preserve existing resources 3. Remove count after verifying with terraform plan
Complete example:
# Before (using count)
variable "availability_zones" {
default = ["us-east-1a", "us-east-1b", "us-east-1c"]
}
resource "aws_subnet" "private" {
count = length(var.availability_zones)
vpc_id = aws_vpc.this.id
cidr_block = cidrsubnet(var.vpc_cidr, 8, count.index)
availability_zone = var.availability_zones[count.index]
tags = {
Name = "private-${var.availability_zones[count.index]}"
}
}
# Reference: aws_subnet.private[0].id
# After (using for_each)
resource "aws_subnet" "private" {
for_each = toset(var.availability_zones)
vpc_id = aws_vpc.this.id
cidr_block = cidrsubnet(var.vpc_cidr, 8, index(var.availability_zones, each.key))
availability_zone = each.key
tags = {
Name = "private-${each.key}"
}
}
# Reference: aws_subnet.private["us-east-1a"].id
# Migration blocks (prevents resource recreation)
moved {
from = aws_subnet.private[0]
to = aws_subnet.private["us-east-1a"]
}
moved {
from = aws_subnet.private[1]
to = aws_subnet.private["us-east-1b"]
}
moved {
from = aws_subnet.private[2]
to = aws_subnet.private["us-east-1c"]
}
# Verify migration:
# terraform plan should show "moved" operations, not destroy/createAfter migration: removing us-east-1b destroys only that subnet; adding an AZ does not churn existing resources; addresses are stable by AZ name.
for_each keys must be known at plan time
for_each (0.12+) requires its key set resolvable during plan.
| Case | Use | Why |
|---|---|---|
| stable key set known at plan | for_each over static map/var | avoids count index churn on insert/remove |
| key set unknowable at plan | count = bool ? 1 : 0 for singleton | keys derived from values unknown until apply |
- ❌
depends_ondoes NOT fixInvalid for_each argument— it orders applies, not plan-time value resolution - ❌ deriving
for_eachkeys from another resource's computed attrs (IDs, ARNs) - ✅ drive
for_eachfrom user-supplied variables or static locals
# ❌ BAD - keys derived from computed IDs; plan fails
resource "aws_eip" "web" {
for_each = toset([for i in aws_instance.web : i.id])
instance = each.key
}
# ✅ GOOD - drive for_each from user-supplied keys
variable "instances" {
type = map(object({ instance_type = string }))
}
resource "aws_instance" "web" {
for_each = var.instances
ami = "ami-0123"
instance_type = each.value.instance_type
}
resource "aws_eip" "web" {
for_each = var.instances
instance = aws_instance.web[each.key].id
}
# ✅ GOOD - singleton when exact ID not known at plan
resource "aws_eip" "bastion" {
count = var.create_bastion ? 1 : 0
instance = aws_instance.bastion[0].id
}---
Modern Terraform Features (1.0+)
Feature Guard Table — Version Floor & Common LLM Errors
Before emitting a feature, verify the runtime floor. Each feature here is also a known hallucination surface — the error pattern column names the mistake to avoid.
| Feature | Min version | Common LLM error pattern |
|---|---|---|
for_each over count for stable identities | 0.12+ | defaults to count for every collection, causing index churn |
try() function | 0.12.20+ | falls back to element(concat()) legacy pattern |
nonsensitive() function | 0.15+ | used to 'unwrap' sensitive outputs into plan artifacts, effectively laundering secrets into logs |
nullable = false | 1.1+ | omits it, letting null silently override defaults |
moved blocks | 1.1+ | omitted during refactor, causing destroy/create |
optional() with defaults | 1.3+ | emits wrapper variables and loose map(any) contracts |
declarative import blocks | 1.5+ | recommends ad-hoc CLI terraform import only |
check blocks | 1.5+ | ignores runtime assertions entirely |
native terraform test | 1.6+ | treats mocked-provider tests as full integration coverage |
| mock providers | 1.7+ | asserts computed values in command = plan mode |
removed blocks | 1.7+ | deletes resources with no lifecycle transition |
| provider-defined functions | 1.8+ | overuses data sources for simple transformations |
| cross-variable validation | 1.9+ | pushes checks into postconditions only |
| S3 native lock-file | 1.10+ | recommends DynamoDB lock table even on 1.10+ |
ephemeral values | 1.10+ | treats as interchangeable with sensitive; ephemeral values are scrubbed from state, sensitive only masks display |
write_only arguments | 1.11+ | uses sensitive = true and assumes state is safe |
If target runtime is below a feature floor, emit the pre-floor fallback explicitly instead of silently downgrading.
try() Function (Terraform 0.12.20+)
Use try() instead of element(concat()):
# ✅ GOOD - Modern try() function
output "security_group_id" {
description = "The ID of the security group"
value = try(aws_security_group.this[0].id, "")
}
output "first_subnet_id" {
description = "ID of first subnet with multiple fallbacks"
value = try(
aws_subnet.public[0].id,
aws_subnet.private[0].id,
""
)
}
# ❌ BAD - Legacy pattern
output "security_group_id" {
value = element(concat(aws_security_group.this[*].id, [""]), 0)
}nullable = false (Terraform 1.1+)
Set nullable = false for non-null variables:
# ✅ GOOD (Terraform 1.1+)
variable "vpc_cidr" {
description = "CIDR block for VPC"
type = string
nullable = false # Passing null uses default, not null
default = "10.0.0.0/16"
}optional() with Defaults (Terraform 1.3+)
Use optional() for object attributes:
# ✅ GOOD - Using optional() for object attributes
variable "database_config" {
description = "Database configuration with optional parameters"
type = object({
name = string
engine = string
instance_class = string
backup_retention = optional(number, 7) # Default: 7
monitoring_enabled = optional(bool, true) # Default: true
tags = optional(map(string), {}) # Default: {}
})
}
# Usage - only required fields needed
database_config = {
name = "mydb"
engine = "mysql"
instance_class = "db.t3.micro"
# Optional fields use defaults
}Moved Blocks (Terraform 1.1+)
Rename resources without destroy/recreate. Omitting moved during a refactor is one of the most common LLM mistakes — the model renames the address and silently turns the rename into destroy/create. Always emit moved in the same change as the rename, then verify terraform plan shows a move operation, not replacement.
# Rename a resource
moved {
from = aws_instance.web_server
to = aws_instance.web
}
# Rename a module
moved {
from = module.old_module_name
to = module.new_module_name
}
# Move resource into for_each
moved {
from = aws_subnet.private[0]
to = aws_subnet.private["us-east-1a"]
}Limits of `moved` (1.1+):
| Limit | Can moved cross this? | Alternative |
|---|---|---|
| Provider boundary | No | use removed (1.7+) + import (1.5+) |
| State file / backend key | No | state mv across backends + pre-migration backup |
| Module removal (module deleted from config) | moved block inside removed module silently stops working | add moved in the parent, not the removed module |
ignore_changes (Lifecycle Escape Hatch)
- ✅ attribute-level
ignore_changes = [tags["X"]]with a comment naming the external system - ❌
ignore_changes = all— hides real drift, turns every attribute unmanaged - ❌ use
ignore_changesto silence noisy plans instead of diagnosing root cause
# ❌ BAD - blanket ignore hides all drift
resource "aws_db_instance" "this" {
lifecycle {
ignore_changes = all
}
}
# ✅ GOOD - narrow ignore with justification
resource "aws_db_instance" "this" {
lifecycle {
# External compliance scanner rewrites this tag hourly
ignore_changes = [tags["LastScanned"]]
}
}Provider-Defined Functions (Terraform 1.8+)
Use provider-specific functions for data transformation:
# AWS provider function example
locals {
# provider::aws::arn_build(partition, service, region, account_id, resource)
# S3 ARNs are global: region and account_id are empty strings.
bucket_arn = provider::aws::arn_build("aws", "s3", "", "", "my-bucket")
}
# Check provider documentation for available functions
# Common providers adding functions: AWS, Azure, Google CloudCross-Variable Validation (Terraform 1.9+)
Reference other variables in validation blocks:
variable "instance_type" {
description = "EC2 instance type"
type = string
}
variable "storage_size" {
description = "Storage size in GB"
type = number
validation {
# Can reference var.instance_type in Terraform 1.9+
condition = !(
var.instance_type == "db.t3.micro" &&
var.storage_size > 1000
)
error_message = "Micro instances cannot have storage > 1000 GB"
}
}
variable "environment" {
description = "Environment name"
type = string
}
variable "backup_retention" {
description = "Backup retention period in days"
type = number
validation {
# Production requires longer retention
condition = (
var.environment == "prod" ? var.backup_retention >= 7 : true
)
error_message = "Production environment requires backup_retention >= 7 days"
}
}Validation Mechanism Timing
Four mechanisms look similar and are routinely confused. Only three actually gate apply.
| Mechanism | When it runs | Can reference | Blocks apply? |
|---|---|---|---|
validation (in variable) | var evaluation, before plan | the variable's own value; other vars on 1.9+ | yes |
precondition (in lifecycle) | before resource create/update | other resources, data sources, vars | yes |
postcondition (in lifecycle) | after apply | the resource's own computed attrs | yes |
check block (1.5+) | every plan + apply | anything | NO — advisory only, warnings not errors |
Write-Only Arguments (Terraform 1.11+)
Always use write-only arguments or external secret management. A common LLM mistake is to mark a variable sensitive = true and assume the value is kept out of state — it is not. sensitive only masks display; write-only arguments (or external secret lookups at runtime) are what actually keep material out of state. Verify on 1.11+: prefer *_wo arguments for credentials; on older runtimes, source secrets from a secret manager and never store them in variables or tfvars.
# ✅ GOOD - External secret with write-only argument
data "aws_secretsmanager_secret" "db_password" {
name = "prod-database-password"
}
data "aws_secretsmanager_secret_version" "db_password" {
secret_id = data.aws_secretsmanager_secret.db_password.id
}
resource "aws_db_instance" "this" {
engine = "mysql"
instance_class = "db.t3.micro"
username = "admin"
# password_wo keeps the resource argument out of state (1.11+),
# but the data source still reads secret_string into state on refresh.
# For true state exclusion: use ephemeral (1.10+), manage_master_user_password,
# or inject via CI env var outside Terraform.
password_wo = data.aws_secretsmanager_secret_version.db_password.secret_string
}
# ❌ BAD - Secret ends up in state file
resource "random_password" "db" {
length = 16
}
resource "aws_db_instance" "this" {
password = random_password.db.result # Stored in state!
}
# ❌ BAD - Variable secret stored in state
resource "aws_db_instance" "this" {
password = var.db_password # Ends up in state file
}nonsensitive() and ephemeral (Terraform 0.15+ / 1.10+)
| Goal | Use | Tradeoff |
|---|---|---|
| derived non-secret incorrectly inferred as sensitive | nonsensitive() (0.15+) | only safe when provably not secret; value enters plan |
| short-lived credential that must never persist | ephemeral (1.10+) | never in state or plan; provider/resource must support it |
| value must persist but not display | sensitive = true | still in state; masks terminal only |
# ✅ GOOD - ephemeral keeps short-lived creds out of state (1.10+)
# requires random provider >= 3.7.0
ephemeral "random_password" "session" {
length = 32
}
# ❌ BAD - unwrapping a real secret to silence a warning
output "db_endpoint" {
value = nonsensitive(aws_db_instance.this.password)
}Dynamic Blocks — Iterator Shadowing + Set Ordering
| Gotcha | Cause | Fix |
|---|---|---|
outer each.* inside nested dynamic | block-name iterator shadows each | iterator = rule rename |
| non-deterministic block order | for_each = toset([...]) on a map/object | use map keyed by stable field |
- ❌ bare
dynamic "ingress"inside outerfor_each—ingress.valueshadowseach.value - ✅ rename inner iterator with
iterator = rule; reference outer viaeach.*
# ✅ GOOD - explicit iterator rename removes ambiguity
resource "aws_security_group" "this" {
for_each = var.security_groups
name = each.key
dynamic "ingress" {
for_each = each.value.rules
iterator = rule
content {
from_port = rule.value.from_port
to_port = rule.value.to_port
protocol = rule.value.protocol
description = each.value.description # outer iterator clear
}
}
}---
Provisioners as Last Resort
| Goal | Use |
|---|---|
| Instance bootstrap | user_data + cloud-init via templatefile() |
| Orchestration with explicit re-run (1.4+) | terraform_data + triggers_replace (list; null_resource uses triggers map) |
| Ongoing OS config | External: Ansible / SSM Run Command / SSM State Manager |
| Last-resort one-shot | terraform_data + provisioner (1.4+) or null_resource (pre-1.4) |
Provisioner costs (`local-exec` + `remote-exec`):
- ❌ Non-idempotent — re-runs duplicate side effects
- ❌ Create-only — updates don't re-run;
when = destroyis fragile - ❌
remote-execneeds SSH/WinRM from runner to target - ❌ No drift detection — Terraform can't observe what scripts changed
- ❌ Script stdout/stderr leaks to CI logs;
sensitivewon't redact it
❌ DON'T — `null_resource` for bootstrap on 1.4+:
resource "null_resource" "bootstrap" {
provisioner "local-exec" {
command = "ssh ec2-user@${aws_instance.web.public_ip} 'bash setup.sh'"
}
}✅ DO — bootstrap via `user_data` + cloud-init:
resource "aws_instance" "web" {
ami = data.aws_ami.al2023.id
instance_type = "t3.small"
user_data = templatefile("${path.module}/cloud-init.yaml", {
app_version = var.app_version
})
user_data_replace_on_change = true
}✅ DO — declarative orchestration on 1.4+:
resource "terraform_data" "migration" {
triggers_replace = [aws_rds_cluster.this.id, var.schema_version]
provisioner "local-exec" {
command = "./run-migration.sh"
}
}---
Version Management
Version Constraint Syntax
# Exact version (avoid unless necessary - inflexible)
version = "5.0.0"
# Pessimistic constraint (recommended for stability)
# The rightmost component is the one that's allowed to increment.
version = "~> 5.0" # 5.x: >= 5.0, < 6.0 — allows 5.1, 5.2, 5.99
version = "~> 5.0.1" # 5.0.x patches only: >= 5.0.1, < 5.1.0
# Range constraints
version = ">= 5.0, < 6.0" # Any 5.x version
version = ">= 5.0.0, < 5.1.0" # Specific minor version range
# Minimum version
version = ">= 5.0" # Any version 5.0 or higher (risky - breaking changes)
# Latest (avoid in production - unpredictable)
# No version specified = always use latest availableVersioning Strategy by Component
Terraform itself:
# versions.tf
terraform {
# Pin to minor version, allow patch updates
required_version = "~> 1.9" # Allows 1.9.x
}Providers:
# versions.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0" # Pin major version, allow minor/patch updates
}
random = {
source = "hashicorp/random"
version = "~> 3.5"
}
}
}Modules:
# Production - pin exact version
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "5.1.2" # Exact version for production stability
}
# Development - allow flexibility
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 5.1" # Allow patch updates in dev
}Update Strategy
Security patches:
- Update immediately
- Test in dev → stage → prod
- Prioritize provider and Terraform core updates
Minor versions:
- Regular maintenance windows (monthly/quarterly)
- Review changelog for breaking changes
- Test thoroughly before production
Major versions:
- Planned upgrade cycles
- Dedicated testing period
- May require code changes
- Update in phases: dev → stage → prod
Version Management Workflow
# Step 1: Lock versions in versions.tf
terraform {
required_version = "~> 1.9"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
# Step 2: Generate lock file (commit this)
terraform init
# Creates .terraform.lock.hcl with exact versions used
# Step 3: Update providers when needed
terraform init -upgrade
# Updates to latest within constraints
# Step 4: Review and test changes before committing
terraform planExample versions.tf Template
terraform {
# Terraform version
required_version = "~> 1.9"
# Provider versions
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
random = {
source = "hashicorp/random"
version = "~> 3.5"
}
null = {
source = "hashicorp/null"
version = "~> 3.2"
}
}
# Backend configuration (optional here, often in backend.tf)
backend "s3" {
bucket = "my-terraform-state"
key = "infrastructure/terraform.tfstate"
region = "us-east-1"
}
}---
Refactoring Patterns
Terraform Version Upgrades
0.12/0.13 → 1.x Migration Checklist
Replace legacy patterns with modern equivalents:
- [ ] Replace
element(concat(...))withtry() - [ ] Add
nullable = falseto variables that shouldn't accept null - [ ] Use
optional()in object types for optional attributes - [ ] Add
validationblocks to variables with constraints - [ ] Migrate secrets to write-only arguments (Terraform 1.11+)
- [ ] Use
movedblocks for resource refactoring (Terraform 1.1+) - [ ] Consider cross-variable validation (Terraform 1.9+)
Example migration:
# Before (0.12 style)
output "security_group_id" {
value = element(concat(aws_security_group.this[*].id, [""]), 0)
}
variable "config" {
type = object({
name = string
size = number
})
}
# After (1.x style)
output "security_group_id" {
description = "The ID of the security group"
value = try(aws_security_group.this[0].id, "")
}
variable "config" {
description = "Configuration settings"
type = object({
name = string
size = optional(number, 100) # Optional with default
})
nullable = false # Don't accept null
}Secrets Remediation
Move secret material out of state into external secret management. Canonical depth lives in security-compliance.md — patterns below are the minimum refactor shape.
❌ BAD — both shapes land the secret in state:
# random_password.result lives in state
resource "random_password" "db" {
length = 16
special = true
}
resource "aws_db_instance" "this" {
password = random_password.db.result
}
# var + sensitive = true still writes to state (sensitive only masks display)
variable "db_password" {
type = string
sensitive = true
}
resource "aws_db_instance" "this" {
password = var.db_password
}✅ GOOD — 1.11+ write-only argument, secret created outside Terraform:
data "aws_secretsmanager_secret_version" "db_password" {
secret_id = "prod-database-password"
}
resource "aws_db_instance" "this" {
engine = "mysql"
username = "admin"
# password_wo: resource argument stays out of state (1.11+).
# Data source still reads secret_string into state on refresh.
# For true state exclusion: ephemeral (1.10+), manage_master_user_password, or CI env var.
password_wo = data.aws_secretsmanager_secret_version.db_password.secret_string
}Pre-1.11 fallback: use the same data source without password_wo; rotation must happen outside Terraform.
Migration steps:
1. Create secret in AWS Secrets Manager outside Terraform 2. Replace random_password / variable with data "aws_secretsmanager_secret_version" 3. On 1.11+: use password_wo 4. Apply, then terraform show | grep -i password — must be empty
---
Locals for Dependency Management
Use locals to hint explicit resource deletion order:
# ✅ GOOD - Forces correct deletion order
# Ensures subnets deleted before secondary CIDR blocks
locals {
# References secondary CIDR first, falling back to VPC
# This forces Terraform to delete subnets before CIDR association
vpc_id = try(
aws_vpc_ipv4_cidr_block_association.this[0].vpc_id,
aws_vpc.this.id,
""
)
}
resource "aws_vpc" "this" {
cidr_block = "10.0.0.0/16"
}
resource "aws_vpc_ipv4_cidr_block_association" "this" {
count = var.add_secondary_cidr ? 1 : 0
vpc_id = aws_vpc.this.id
cidr_block = "10.1.0.0/16"
}
resource "aws_subnet" "public" {
# Uses local instead of direct reference
# Creates implicit dependency on CIDR association
vpc_id = local.vpc_id
cidr_block = "10.1.0.0/24"
}
# Without local: Terraform might try to delete CIDR before subnets → ERROR
# With local: Subnets deleted first, then CIDR association, then VPC ✓Common use cases:
- VPC with secondary CIDR blocks
- Resources depending on optional configurations
- Complex deletion-order requirements
---
LLM Mistake Checklist — Code Patterns
Common model mistakes when generating HCL. Correct these before returning code:
- defaults to
countfor every collection — preferfor_eachwith stable keys whenever identity matters - omits
movedblocks during rename/refactor, silently turning the change into destroy/create - builds
for_eachkeys from computed IDs not known until apply — planning will fail - uses list index as long-lived identity (
count.index) instead of business-meaningful keys - marks variables
sensitive = trueand assumes the value stays out of state — on 1.11+ usewrite_only/*_woarguments - falls back to
element(concat(...))instead oftry()on 0.12.20+ - accepts untyped
map(any)/anyfor long-lived module contracts instead ofoptional()with typed defaults (1.3+) - suggests
terraform state mvwheremovedblocks are safer and reviewable - recommends ad-hoc CLI
terraform importinstead of declarativeimportblocks (1.5+) - emits an exact
version = "5.0.0"pin where~> 5.0would be more maintainable - silently emits 1.11+ features (S3 native lock,
write_only,removed) without checking the runtime floor - uses
nonsensitive()to "fix" a sensitive value appearing in plan output — this leaks secrets into CI artifacts - conflates
sensitive = truewithephemeral(1.10+); onlyephemeralactually stays out of state - writes a
movedblock expecting it to cross provider boundaries; it cannot - leaves
movedblocks inside a module that itself is being removed — the moves silently no-op, resources get destroyed - emits CLI
terraform importin automation when declarativeimportblocks (1.5+) give a reviewable, VCS-tracked alternative - emits
ignore_changes = allor broad ignore lists to silence plan output instead of diagnosing drift root cause - uses
checkblock expecting it to block apply;checkis advisory, emits warnings only. Useprecondition/postconditionto gate. - uses
each.valueinside adynamicblock intending the outer iterator — shadowed by the inner block name; rename withiterator = ... - emits hardcoded cloud IDs/ARNs (
vpc-0abc..., pattern-matchedarn:aws:iam::patterns) from training data instead of using data sources or input variables - pairs
password_wowithaws_secretsmanager_secret_version— the data source still readssecret_stringinto state on refresh. Useephemeral(1.10+) or CI-injected env var. - iterates
dynamicblocks overtoset(...)of maps/objects — the set's undefined ordering causes non-deterministic block ordering in the plan diff; sort the list or use a map keyed by a stable field
---
Back to: Main Skill File
Module Development Patterns
Part of: terraform-skill
Purpose: Best practices for Terraform/OpenTofu module development
This document provides detailed guidance on creating reusable, maintainable Terraform modules. For high-level principles, see the main skill file.
---
Table of Contents
1. Module Hierarchy 2. Architecture Principles 3. Module Structure 4. Variable Best Practices 5. Output Best Practices 6. Common Patterns 7. Anti-patterns to Avoid 8. Testing Philosophy & Patterns
---
Module Hierarchy
Module Type Classification
| Type | When to Use | Scope | Example |
|---|---|---|---|
| Resource Module | Single logical group of connected resources | Tightly coupled resources that always work together | VPC + subnets, Security group + rules, IAM role + policies |
| Infrastructure Module | Collection of resource modules for a purpose | Multiple resource modules in one region/account | Complete networking stack, Application infrastructure |
| Composition | Complete infrastructure | Spans multiple regions/accounts, orchestrates infrastructure modules | Multi-region deployment, Production environment |
Hierarchy: Resource → Resource Module → Infrastructure Module → Composition
Resource Module
Characteristics:
- Smallest building block
- Single logical group of resources
- Highly reusable across projects
- Minimal external dependencies
- Clear, focused purpose
Examples:
modules/
├── vpc/ # Resource module
│ ├── main.tf # VPC + subnets + route tables
│ ├── variables.tf
│ └── outputs.tf
├── security-group/ # Resource module
│ ├── main.tf # Security group + rules
│ ├── variables.tf
│ └── outputs.tf
└── rds/ # Resource module
├── main.tf # RDS instance + subnet group
├── variables.tf
└── outputs.tfInfrastructure Module
Characteristics:
- Combines multiple resource modules
- Purpose-specific (e.g., "web application infrastructure")
- May span multiple services
- Region or account-specific
- Moderate reusability
Examples:
modules/
└── web-application/ # Infrastructure module
├── main.tf # Orchestrates multiple resource modules
├── variables.tf
├── outputs.tf
└── README.md
# main.tf contents:
module "vpc" {
source = "../vpc"
}
module "alb" {
source = "../alb"
vpc_id = module.vpc.vpc_id
}
module "ecs" {
source = "../ecs"
vpc_id = module.vpc.vpc_id
subnets = module.vpc.private_subnet_ids
}Composition
Characteristics:
- Highest level of abstraction
- Complete environment or application
- Combines infrastructure modules
- Environment-specific (dev, staging, prod)
- Not reusable (environment-specific values)
Examples:
environments/
├── prod/ # Composition
│ ├── main.tf # Complete production environment
│ ├── backend.tf # Remote state configuration
│ ├── terraform.tfvars # Production-specific values
│ └── variables.tf
├── staging/ # Composition
│ ├── main.tf
│ ├── backend.tf
│ ├── terraform.tfvars
│ └── variables.tf
└── dev/ # Composition
├── main.tf
├── backend.tf
├── terraform.tfvars
└── variables.tfDecision Tree: Which Module Type?
Question 1: Is this environment-specific configuration?
├─ YES → Composition (environments/prod/, environments/staging/)
└─ NO → Continue
Question 2: Does it combine multiple infrastructure concerns?
├─ YES → Infrastructure Module (modules/web-application/)
└─ NO → Continue
Question 3: Is it a focused group of related resources?
└─ YES → Resource Module (modules/vpc/, modules/rds/)File Organization Standards
Required files in all modules:
main.tf # Resource definitions, module calls, data sources
variables.tf # Input variable declarations
outputs.tf # Output value declarations
versions.tf # Provider and Terraform version constraints
README.md # Usage documentationConditional files:
terraform.tfvars # ONLY at composition level (NEVER in modules)
locals.tf # For complex local value calculations
data.tf # Optional: Data sources (if main.tf gets large)
backend.tf # ONLY at composition level (remote state config)Required structure for Terraform Registry publishing; keeps navigation consistent across modules.
---
Architecture Principles
1. Smaller Scopes = Better Performance + Reduced Blast Radius
Faster plan/apply, isolated failures, parallel team development.
Example:
# ❌ BAD - One massive composition with everything
environments/prod/
main.tf # 2000 lines, manages VPC, EC2, RDS, S3, IAM, everything
# Takes 10+ minutes to plan
# One mistake affects entire infrastructure
# ✅ GOOD - Separated by concern
environments/prod/
networking/ # VPC, subnets, route tables
compute/ # EC2, ASG, ALB
data/ # RDS, ElastiCache
storage/ # S3, EFS
iam/ # IAM roles, policies2. Always Use Remote State
- ❌ local
terraform.tfstate— no locking, no backup, no team access - ✅ remote backend — locking, versioning, encryption, audit log
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/networking/terraform.tfstate"
region = "us-east-1"
encrypt = true
use_lockfile = true # Terraform 1.10+; native S3 locking
# Pre-1.10 runtime: use dynamodb_table = "terraform-locks" instead
}
}3. Use terraform_remote_state Sparingly — Only at True Ownership Boundaries
Pattern: Connect separately-owned compositions via remote state data sources. Reserve it for genuine team/lifecycle boundaries, not as convenient glue inside a single-team stack.
Use it when ALL of these are true:
- Consumer and producer are owned by different teams or have different release cadences
- The producer's state is already split for lifecycle reasons (networking vs. compute vs. data)
- You cannot reasonably pass the same values as module inputs
Do NOT use it when:
- You control both stacks and can wire via module outputs
- You're reading values that would be better served by a cloud data source (e.g.,
aws_vpcby tag) - You're reaching across >2 remote states in one composition — that is a signal to reshape boundaries, not add more wiring
Common LLM mistakes:
- reaches for
terraform_remote_stateas default integration pattern - chains many
terraform_remote_statereads, creating hidden cross-stack coupling - reads values that can drift at the provider level (use cloud data sources instead)
At real boundaries, outputs from one stack become typed inputs to another — teams release independently without shared mutable state.
Example:
# environments/prod/networking/outputs.tf
output "vpc_id" {
description = "ID of the production VPC"
value = aws_vpc.this.id
}
output "private_subnet_ids" {
description = "List of private subnet IDs"
value = aws_subnet.private[*].id
}
# environments/prod/compute/main.tf
data "terraform_remote_state" "networking" {
backend = "s3"
config = {
bucket = "my-terraform-state"
key = "prod/networking/terraform.tfstate"
region = "us-east-1"
}
}
module "ec2" {
source = "../../modules/ec2"
vpc_id = data.terraform_remote_state.networking.outputs.vpc_id
subnet_ids = data.terraform_remote_state.networking.outputs.private_subnet_ids
}- ✅ document which outputs are consumed externally; version outputs, never break downstream consumers silently
- ✅ prefer cloud data sources (
aws_vpcby tag) overterraform_remote_statefor provider-managed resources
4. Keep Resource Modules Simple
Principles:
- Don't hardcode values
- Use variables for all configurable parameters
- Use data sources for external dependencies
- Focus on single responsibility
Example:
# ❌ BAD - Hardcoded values in resource module
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0" # Hardcoded
instance_type = "t3.large" # Hardcoded
subnet_id = "subnet-12345678" # Hardcoded
tags = {
Environment = "production" # Hardcoded
}
}
# ✅ GOOD - Parameterized resource module
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
}
}
resource "aws_instance" "web" {
ami = var.ami_id != "" ? var.ami_id : data.aws_ami.ubuntu.id
instance_type = var.instance_type
subnet_id = var.subnet_id
tags = var.tags
}Cross-cloud resource map
| Resource | AWS | Azure | GCP |
|---|---|---|---|
| Network | aws_vpc | azurerm_virtual_network | google_compute_network |
| Subnet | aws_subnet | azurerm_subnet | google_compute_subnetwork |
| Compute instance | aws_instance | azurerm_linux_virtual_machine | google_compute_instance |
| Managed relational DB | aws_db_instance / aws_rds_cluster | azurerm_*_flexible_server | google_sql_database_instance |
| Object storage | aws_s3_bucket | azurerm_storage_account + azurerm_storage_container | google_storage_bucket |
5. Composition Layer: Environment-Specific Values Only
Pattern: Compositions provide concrete values, modules provide abstractions
# ✅ GOOD - Composition with environment-specific values
# environments/prod/main.tf
module "vpc" {
source = "../../modules/vpc"
cidr_block = "10.0.0.0/16"
availability_zones = ["us-east-1a", "us-east-1b", "us-east-1c"]
enable_nat_gateway = true
single_nat_gateway = false # HA for production
tags = {
Environment = "production"
ManagedBy = "Terraform"
CostCenter = "engineering"
}
}
module "rds" {
source = "../../modules/rds"
instance_class = "db.r5.xlarge" # Production sizing
allocated_storage = 500 # Production sizing
multi_az = true # HA for production
backup_retention = 30 # Long retention for prod
vpc_id = module.vpc.vpc_id
subnet_ids = module.vpc.private_subnet_ids
tags = {
Environment = "production"
}
}---
Module Structure
Standard Layout
my-module/
├── README.md # Usage documentation
├── LICENSE # MIT or Apache 2.0 (for public modules)
├── .pre-commit-config.yaml # Pre-commit hooks configuration
├── main.tf # Primary resources
├── variables.tf # Input variables with descriptions
├── outputs.tf # Output values
├── versions.tf # Provider version constraints
├── examples/
│ ├── simple/ # Minimal working example
│ └── complete/ # Full-featured example
└── tests/ # Test files
└── module_test.tftest.hcl # Or .goFile Role
README.md— module purpose, first file users seeLICENSE— legal terms for public modules (MIT or Apache 2.0).pre-commit-config.yaml— automated validation before commitsmain.tf— primary resources, keep focusedvariables.tf— all inputs, with descriptionsoutputs.tf— all outputs, with descriptionsversions.tf— pinned provider versionsexamples/— docs + test fixturestests/— automated tests
License Files
- ✅ Public modules / open-source projects — include LICENSE (MIT = permissive; Apache 2.0 = permissive + patent grant)
- ❌ Private internal modules / environment-specific configs — optional
- ❌ Do NOT store LICENSE templates in this skill; generate them on demand from user preference
Terraform vs OpenTofu Preference
HCL is identical; choice affects commands, README, CI invocations, binary references only. Ask before generating if not specified.
Inference signals (when a project already exists):
required_versionconstraint or comments pinning the runtime- CI pipelines invoking
terraformvstofuexplicitly .terraform.lock.hclprovenance (check commit history / init script)- ❌
.terraform/working directory — both runtimes share it, not a differentiator
If signals are mixed, ask the user rather than guessing, or show both command variants in docs.
Document the chosen runtime in the module README:
## Requirements
| Name | Version |
|------|---------|
| [terraform/tofu] | >= 1.7.0 |
| aws | ~> 5.0 |---
Variable Best Practices
Complete Example
variable "instance_type" {
description = "EC2 instance type for the application server"
type = string
default = "t3.micro"
validation {
condition = contains(["t3.micro", "t3.small", "t3.medium"], var.instance_type)
error_message = "Instance type must be t3.micro, t3.small, or t3.medium."
}
}
variable "tags" {
description = "Tags to apply to all resources"
type = map(string)
default = {}
}
variable "enable_monitoring" {
description = "Enable CloudWatch detailed monitoring"
type = bool
default = true
}Key Principles
- ✅ Always include `description` - Helps users understand the variable
- ✅ Use explicit `type` constraints - Catches errors early
- ✅ Provide sensible `default` values - Where appropriate
- ✅ Add `validation` blocks - For complex constraints
- ✅ Use `sensitive = true` - For secrets (Terraform 0.14+)
Variable Naming
# ✅ Good: Context-specific
var.vpc_cidr_block # Not just "cidr"
var.database_instance_class # Not just "instance_class"
var.application_port # Not just "port"
# ❌ Bad: Generic names
var.name
var.type
var.valueProvider Requirements and Alias Passing
- ✅ Child module declares aliased providers:
configuration_aliases = [aws.primary, aws.replica] - ✅ Caller passes them explicitly:
providers = { aws.primary = aws.<caller-alias> }on themoduleblock - ❌ Default provider inheritance applies ONLY to a single unaliased provider — never for aliases
Child module — declare aliases in versions.tf, bind per resource:
# modules/replicated-s3/versions.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
configuration_aliases = [aws.primary, aws.replica]
}
}
}
# in any resource:
provider = aws.primaryCaller — pass the providers map on the module block:
module "bucket" {
source = "./modules/replicated-s3"
bucket_name = "app-data"
providers = {
aws.primary = aws.us_east_1
aws.replica = aws.eu_west_1
}
}❌ DON'T — missing providers map on the module call:
module "bucket" {
source = "./modules/replicated-s3"
bucket_name = "app-data"
# MISSING: providers = { aws.primary = ..., aws.replica = ... }
# Plan fails: "No configuration for provider aws.primary"
}---
Output Best Practices
Complete Example
output "instance_id" {
description = "ID of the created EC2 instance"
value = aws_instance.this.id
}
output "instance_arn" {
description = "ARN of the created EC2 instance"
value = aws_instance.this.arn
}
output "private_ip" {
description = "Private IP address of the instance"
value = aws_instance.this.private_ip
sensitive = false # Explicitly document sensitivity
}
output "connection_info" {
description = "Connection information for the instance"
value = {
id = aws_instance.this.id
private_ip = aws_instance.this.private_ip
public_dns = aws_instance.this.public_dns
}
}Key Principles
- ✅ Always include `description` - Explain what the output is for
- ✅ Mark sensitive outputs - Use
sensitive = true - ✅ Return objects for related values - Groups logically related data
- ✅ Document intended use - What should consumers do with this?
---
Common Patterns
Iteration: for_each vs count
Use for_each with stable keys whenever a collection has meaningful identity — removing or reordering an element leaves unrelated addresses untouched. Reserve count for optional singletons (0 or 1) and cases where keys cannot be known at plan time.
For the decision matrix, migration playbook, and known-at-plan failure patterns, see Code Patterns: count vs for_each.
✅ DO: Separate Root Module from Reusable Modules
# Root module (environment-specific)
prod/
main.tf # Calls modules with prod-specific values
variables.tf # Environment-specific variables
# Reusable module
modules/webapp/
main.tf # Generic, parameterized resources
variables.tf # Configurable inputsRoot modules are environment-specific; reusable modules are generic.
✅ DO: Use Locals for Computed Values
locals {
common_tags = merge(
var.tags,
{
Environment = var.environment
ManagedBy = "Terraform"
}
)
instance_name = "${var.project}-${var.environment}-instance"
}
resource "aws_instance" "app" {
tags = local.common_tags
# ...
}✅ DO: Version Your Modules
# In consuming code
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 5.0" # Pin to major version
# module inputs...
}Prevents unexpected breaking changes from upstream major bumps.
---
Anti-patterns to Avoid
❌ DON'T: Hard-code Environment-Specific Values
# Bad: Module is locked to production
resource "aws_instance" "app" {
instance_type = "m5.large" # Should be variable
tags = {
Environment = "production" # Should be variable
}
}Fix: Make everything configurable:
resource "aws_instance" "app" {
instance_type = var.instance_type
tags = var.tags
}❌ DON'T: Create God Modules
# Bad: One module does everything
module "everything" {
source = "./modules/app-infrastructure"
# Creates VPC, EC2, RDS, S3, IAM, CloudWatch, etc.
}Problem: Hard to test, hard to reuse, hard to maintain.
Fix: Break into focused modules:
module "networking" {
source = "./modules/vpc"
}
module "compute" {
source = "./modules/ec2"
vpc_id = module.networking.vpc_id
}
module "database" {
source = "./modules/rds"
vpc_id = module.networking.vpc_id
}❌ DON'T: Use count or for_each in Root Modules for Different Environments
# Bad: All environments in one root module
resource "aws_instance" "app" {
for_each = toset(["dev", "staging", "prod"])
instance_type = each.key == "prod" ? "m5.large" : "t3.micro"
}Problem: Can't have separate state files, blast radius is huge.
Fix: Use separate root modules:
environments/
dev/
main.tf
staging/
main.tf
prod/
main.tf❌ DON'T: Use terraform_remote_state Everywhere
Use module outputs when possible. Reserve remote state for ownership boundaries between teams. See Use terraform_remote_state Sparingly for the full rule set.
---
Module Naming Conventions
Public Modules
Follow the Terraform Registry convention:
terraform-<PROVIDER>-<NAME>
Examples:
terraform-aws-vpc
terraform-aws-eks
terraform-google-networkPrivate Modules
Use organization-specific prefixes:
<ORG>-terraform-<PROVIDER>-<NAME>
Examples:
acme-terraform-aws-vpc
acme-terraform-aws-rds---
Module Release Checklist
Before publishing or handing off a reusable module:
- [ ] Runtime and provider choice explicit (Terraform vs OpenTofu, version floor in
required_version) - [ ] Public vs private scope decided (affects naming + license)
- [ ]
examples/directory with at leastminimalandcomplete - [ ] Tests written (native
terraform teston 1.6+, or Terratest) — see testing-frameworks.md - [ ] README documents all inputs/outputs (Description → Usage → Inputs → Outputs → Requirements)
- [ ] Module source pinned with
versionin consumer code - [ ]
pre-commit-terraformhooks configured (terraform_fmt,terraform_validate,terraform_tflint,terraform_docs), pinned to a specificrev - [ ]
LICENSEpresent for public modules (MIT or Apache-2.0) - [ ]
.gitignoreexcludes.terraform/,*.tfstate*,*.tfvars, override files, and editor artifacts
---
Module Testing — Pointer
Module testing (what to test, tiered layers, mocking, idempotency, cost control, strategy by module type) is canonical in Testing Frameworks. Module-specific rules that belong with the module contract:
- Every reusable module must exercise its
validationblocks in tests — reject cases are as important as happy paths. - Tier tests by module role: resource modules → input validation + attribute assertions; infrastructure modules → composition + cross-module wiring; compositions → smoke-plan + production-like values + remote-state connectivity.
- Mock providers (1.7+) for unit tests; reserve real cloud runs for main-branch or scheduled jobs.
---
LLM Mistake Checklist — Modules
Common model mistakes to correct when generating or reviewing modules:
- bundles unrelated resources into one "god module" instead of splitting by single responsibility
- hardcodes environment-specific values (
instance_type = "m5.large",Environment = "production") inside a reusable module - accepts untyped
map(any)/anyfor core module inputs instead of typed objects withoptional()defaults - exposes entire provider or resource objects as outputs, leaking the whole contract instead of a stable subset
- omits
descriptionon inputs and outputs, forcing consumers to read the implementation - uses
thisfor multiple resources of the same type — reservethisfor genuine singletons only - reaches for
terraform_remote_stateinside a single team's stack instead of wiring via module outputs - floats module sources (no
versionpin) in consumer code - pushes environment-specific policy (prod-only allowlists, region pins) into primitive/resource modules where it cannot be overridden
- omits
configuration_aliasesin a multi-provider child module'srequired_providers— callers cannot pass aliased providers - drops the
providers = { aws = aws.region }map from the module call on multi-region or multi-account deploys — resources land on the default provider
---
Back to: Main Skill File
Quick Reference
Part of: terraform-skill
Purpose: Command cheat sheets and decision flowcharts
This document provides quick lookup tables, command references, and decision flowcharts for rapid consultation during development.
---
Table of Contents
1. Command Cheat Sheet 2. Decision Flowchart 3. Version-Specific Guidance 4. Troubleshooting Guide 5. Migration Paths
---
Command Cheat Sheet
Static Analysis
Works with both terraform and tofu commands:
# Format and validate
terraform fmt -recursive -check # or: tofu fmt -recursive -check
terraform validate # or: tofu validate
# Linting
tflint --init && tflint
# Security scanning
checkov -d .Native Tests (1.6+)
# Run all tests
terraform test # or: tofu test
# Run tests in specific directory
terraform test -test-directory=tests/unit/
# Verbose output
terraform test -verbosePlan Validation
# Generate and review plan
terraform plan -out tfplan # or: tofu plan -out tfplan
# Convert plan to pretty JSON
terraform show -json tfplan | jq -r '.' > tfplan.json
# Check for specific changes
terraform show tfplan | grep "will be created"State Management
# View all resources in state
terraform state list
# Show specific resource details
terraform state show aws_instance.web
# Move/rename resource in state (refactoring)
terraform state mv aws_instance.old aws_instance.new
terraform state mv aws_instance.app module.compute.aws_instance.app
# Remove resource from state (keeps actual resource)
terraform state rm aws_instance.temporary
# Import existing resource into state
terraform import aws_instance.web i-1234567890abcdef0
# Import using import blocks (1.5+)
# Define in .tf: import { to = aws_instance.web, id = "i-123..." }
# Note: File must not exist — Terraform refuses to overwrite.
terraform plan -generate-config-out=imported.tf
# Detect configuration drift
terraform plan -refresh-only
# Update state to match reality (no infrastructure changes)
terraform apply -refresh-only
# Backup state to file
terraform state pull > backup-$(date +%Y%m%d).tfstate
# Restore state from backup (DANGEROUS)
terraform state push backup.tfstate
# Force unlock stuck state lock
# Default: prompts for y/N confirmation
terraform force-unlock LOCK_ID
# CI-friendly (skips prompt):
terraform force-unlock -force LOCK_IDState Backend Migration
# Migrate from local to remote backend
# 1. Add backend config to backend.tf
# 2. Run migration
terraform init -migrate-state
# Change backend without migrating state
terraform init -reconfigure
# Pass backend config at runtime
terraform init \
-backend-config="key=prod/terraform.tfstate" \
-backend-config="dynamodb_table=terraform-locks"
# Or use config file
terraform init -backend-config=backend-prod.hcl---
Decision Flowchart
Testing Approach Selection
Need to test Terraform/OpenTofu code?
│
├─ Just syntax/format?
│ └─ terraform/tofu validate + fmt
│
├─ Static security scan?
│ └─ trivy + checkov
│
├─ Terraform/OpenTofu 1.6+?
│ ├─ Simple logic test?
│ │ └─ Native terraform/tofu test
│ │
│ └─ Complex integration?
│ └─ Terratest
│
└─ Pre-1.6?
├─ Go team?
│ └─ Terratest
│
└─ Neither?
└─ Plan to upgrade Terraform/OpenTofuModule Development Workflow
1. Plan
├─ Define inputs (variables.tf)
├─ Define outputs (outputs.tf)
└─ Document purpose (README.md)
2. Implement
├─ Create resources (main.tf)
├─ Pin versions (versions.tf)
└─ Add examples (examples/simple, examples/complete)
3. Test
├─ Static analysis (validate, fmt, lint)
├─ Unit tests (native or Terratest)
└─ Integration tests (examples/)
4. Document
├─ Update README with usage
├─ Document inputs/outputs
└─ Add CHANGELOG
5. Publish
├─ Tag version (git tag v1.0.0)
├─ Push to registry
└─ Announce changes---
Version-Specific Guidance
Terraform 1.0-1.5
- ❌ No native testing framework
- ✅ Use Terratest
- ✅ Focus on static analysis
- ✅ terraform plan validation
Terraform 1.6+ / OpenTofu 1.6+
- ✅ NEW: Native
terraform test/tofu testframework with.tftest.hclfiles - ✅ Consider migrating simple tests from Terratest
- ✅ Keep Terratest for complex integration
- ✅ Import blocks from 1.5 available for declarative imports with
-generate-config-out
Terraform 1.7+ / OpenTofu 1.7+
- ✅ NEW: Mock providers for unit testing
- ✅ Reduce costs with mocking
- ✅ Use real integration tests for final validation
- ✅ Faster test iteration
Terraform vs OpenTofu Comparison
| Factor | Terraform | OpenTofu |
|---|---|---|
| Licensing | Business Source License 1.1 (BUSL-1.1) | Mozilla Public License 2.0 (MPL 2.0) |
| Governance | HashiCorp (single vendor) | Linux Foundation (community-driven) |
| Latest Version | 1.14+ | 1.11+ |
| Native Testing | 1.6+ | 1.6+ |
| Mock Providers | 1.7+ | 1.7+ |
| Feature Parity | Reference implementation | Compatible fork with some additions |
| Enterprise Support | HCP Terraform, Terraform Cloud | Multiple vendors |
| Migration Path | N/A | Drop-in replacement for Terraform ≤1.5.x; feature-compatible fork thereafter with divergence on encryption, mock providers, provider functions, and other post-1.6 additions. Verify specific feature availability per version. |
Choose Terraform for: HCP Terraform / Terraform Cloud, HashiCorp enterprise support, first access to latest features.
Choose OpenTofu for: open-source governance, vendor-lock-in avoidance, BUSL-1.1 incompatibility.
Since OpenTofu 1.6 the platforms have diverged — this skill notes version floors explicitly and shows both terraform and tofu commands. When creating modules, Claude asks preference to pick commands/docs.
---
Troubleshooting Guide
Issue: Tests fail in CI but pass locally
Symptoms:
- Tests pass on your machine
- Same tests fail in GitHub Actions/GitLab CI
Common Causes: 1. Different Terraform/provider versions 2. Different environment variables 3. Different AWS credentials/permissions
Solution:
# versions.tf - Pin versions explicitly
terraform {
required_version = ">= 1.6.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0" # Pin to major version
}
}
}Issue: Parallel tests conflict
Symptoms:
- Tests fail when run in parallel
- Error: "ResourceAlreadyExistsException"
Cause: Resource naming collisions
Solution:
// Use unique identifiers
import "github.com/gruntwork-io/terratest/modules/random"
uniqueId := random.UniqueId()
bucketName := fmt.Sprintf("test-bucket-%s", uniqueId)Issue: High test costs
Symptoms:
- AWS bill increasing from tests
- Many orphaned resources in test account
Solutions:
1. Use mocking for unit tests (Terraform 1.7+)
mock_provider "aws" { ... }2. Implement resource TTL tags
Vars: map[string]interface{}{
"tags": map[string]string{
"Environment": "test",
"TTL": "2h",
},
}3. Run integration tests only on main branch
if: github.ref == 'refs/heads/main'4. Use smaller instance types
instance_type = "t3.micro" # Not "m5.large"5. Share test resources when safe
- VPCs, security groups (rarely change)
- Don't share: instances, databases (change often)
Issue: State lock is stuck
Symptoms:
Error: Error acquiring the state lock
Lock Info:
ID: a1b2c3d4-e5f6-7890-abcd-ef1234567890
Who: user@hostname
Created: 2026-01-20 12:00:00Common Causes: 1. Terraform process crashed or was killed 2. Network interruption during operation 3. CI/CD job terminated unexpectedly
Solution:
# 1. Verify the operation is NOT actually running
# Check the host mentioned in lock info
ssh user@hostname "ps aux | grep terraform"
# Or check CI/CD job status
# GitHub Actions: Check workflow runs
# GitLab CI: Check pipeline jobs
# 2. Only if confirmed the operation is not running:
terraform force-unlock LOCK_ID
# 3. Document why you unlocked
echo "Force-unlocked due to CI job timeout" > unlock-notes.txtPrevention:
# GitHub Actions - Use concurrency control
concurrency:
group: terraform-${{ github.ref }}
cancel-in-progress: false # Wait, don't cancelIssue: State file is corrupted or lost
Symptoms:
- Error: "state snapshot was created by Terraform v1.8.0"
- Error: "Failed to load state"
- State file missing or unreadable
Solutions:
If versioning enabled (S3):
# List versions
aws s3api list-object-versions \
--bucket my-terraform-state \
--prefix prod/terraform.tfstate
# Restore previous version
aws s3api get-object \
--bucket my-terraform-state \
--key prod/terraform.tfstate \
--version-id PREVIOUS_VERSION_ID \
terraform.tfstate.restored
# Push restored state
terraform state push terraform.tfstate.restoredIf no backup exists:
# Recreate state by importing all resources
terraform import aws_vpc.main vpc-12345678
terraform import aws_subnet.private[0] subnet-abcd1234
# ... continue for all resources
# Or use import blocks (1.5+)
# In .tf file:
# import { to = aws_vpc.main, id = "vpc-12345678" }
# Note: File must not exist — Terraform refuses to overwrite.
terraform plan -generate-config-out=imported.tfIssue: Configuration drift detected
Symptoms:
Note: Objects have changed outside of TerraformCause: Manual changes in console or by other tools
Solutions:
# View drift
terraform plan -refresh-only
# Accept drift (update state to match reality)
terraform apply -refresh-only
# Or fix drift (update resources to match config)
terraform apply
# Prevent drift with detective controls
# - Enable CloudTrail
# - Use AWS Config rules
# - Regular terraform plan in CIIssue: Cannot migrate state between backends
Symptoms:
terraform init -migrate-statefails- Backend authentication errors
Solutions:
# Ensure credentials are configured
export AWS_PROFILE=terraform
# or
export AWS_ACCESS_KEY_ID=...
export AWS_SECRET_ACCESS_KEY=...
# Try migration again
terraform init -migrate-state
# If still failing, manual migration:
# 1. Pull state from old backend
terraform state pull > old-state.json
# 2. Switch backend config
# Edit backend.tf
# 3. Initialize new backend
terraform init -reconfigure
# 4. Push state to new backend
terraform state push old-state.json---
Migration Paths
From Manual Testing → Automated
Phase 1: Static analysis
terraform validate
terraform fmt -checkPhase 2: Plan review
terraform plan -out=tfplan
# Manual reviewPhase 3: Automated tests
- Native tests (1.6+)
- OR Terratest
Phase 4: CI/CD integration
- GitHub Actions / GitLab CI
- Automated apply on main branch
From Terratest → Native Tests (1.6+)
Strategy: Gradual migration
1. Keep Terratest for:
- Complex integration tests
- Multi-step workflows
- Cross-provider tests
2. Migrate to native tests:
- Simple unit tests
- Logic validation
- Mock-friendly tests
3. During transition:
- Maintain both frameworks
- Gradually increase native test coverage
- Remove Terratest tests once replaced
Example: Mixed approach
tests/
├── unit/ # Native tests
│ └── validation.tftest.hcl
└── integration/ # Terratest
└── complete_test.goFrom Terraform → OpenTofu
OpenTofu is a drop-in replacement for Terraform ≤1.5.x; a feature-compatible fork thereafter with divergence on encryption, mock providers, provider functions, and other post-1.6 additions. See the Terraform vs OpenTofu Comparison and verify per-version feature availability.
1. HCL ≤1.5.x — no code changes; providers and state files compatible. Verify post-1.6 features per version. 2. CI/CD — swap terraform for tofu in init/plan/apply invocations. 3. Docs — note OpenTofu compatibility in README; update workflow templates to the tofu binary.
---
Pre-Commit Checklist
Formatting & Validation
Run these commands before every commit:
# Format all Terraform files
terraform fmt -recursive
# Validate configuration
terraform validateNaming Convention Review
- [ ] All identifiers use
_not- - [ ] No resource names repeat resource type (no
aws_vpc.main_vpc) - [ ] Single-instance resources named
thisor descriptive name - [ ] Variables have plural names for lists/maps (
subnet_idsnotsubnet_id) - [ ] All variables have descriptions
- [ ] All outputs have descriptions
- [ ] Output names follow
{name}_{type}_{attribute}pattern - [ ] No double negatives in variable names
Code Structure Review
- [ ]
count/for_eachat top of resource blocks (blank line after) - [ ]
tagsas last real argument in resources - [ ]
depends_onafter tags (if used) - [ ]
lifecycleat end of resource (if used) - [ ] Variables ordered: description → type → default → sensitive → nullable → validation
- [ ] Only
#comments used (no//or/* */)
Modern Features Check
- [ ] Using
try()notelement(concat()) - [ ] Secrets use write-only arguments or external data sources (not in state)
- [ ]
nullable = falseset on non-null variables - [ ]
optional()used in object types where applicable (Terraform 1.3+) - [ ] Variable validation blocks added where constraints needed
- [ ] Consider cross-variable validation for related variables (Terraform 1.9+)
Architecture Review
- [ ]
terraform.tfvarsonly at composition level (not in modules) - [ ] Remote state configured (never local state)
- [ ] Resource modules don't hardcode values (use variables/data sources)
- [ ]
terraform_remote_stateused for cross-composition dependencies - [ ] File structure follows standard: main.tf, variables.tf, outputs.tf, versions.tf
Documentation Check
Required documentation for all modules:
- [ ] README.md exists with absolute links (Terraform Registry compatibility)
- [ ] All variables documented in README with descriptions and types
- [ ] All outputs documented in README with descriptions
- [ ] Usage examples provided showing how to use the module
- [ ] Version requirements specified (Terraform version, provider versions)
---
Version Management Quick Reference
Constraint Syntax
| Syntax | Meaning | Use Case |
|---|---|---|
"5.0.0" | Exact version | Avoid (inflexible) |
"~> 5.0" | Pessimistic (>= 5.0, < 6.0 — any 5.x) | Allow minor and patch updates within 5.x |
"~> 5.0.1" | Pessimistic (>= 5.0.1, < 5.1.0 — 5.0.x patches) | Lock to 5.0.x patch updates only |
">= 5.0, < 6.0" | Range | Any 5.x version |
">= 5.0" | Minimum | Risky (breaking changes) |
Strategy by Component
| Component | Recommendation | Example |
|---|---|---|
| Terraform | Pin minor, allow patch | required_version = "~> 1.9" |
| Providers | Pin major, allow minor/patch | version = "~> 5.0" |
| Modules (prod) | Pin exact version | version = "5.1.2" |
| Modules (dev) | Allow patch updates | version = "~> 5.1" |
Update Workflow
# Step 1: Lock versions initially
terraform init # Creates .terraform.lock.hcl
# Step 2: Update to latest within constraints
terraform init -upgrade # Updates providers
# Step 3: Review changes
terraform plan
# Step 4: Commit lock file
git add .terraform.lock.hcl
git commit -m "Update provider versions"Update Strategy
Security patches:
- Update immediately
- Test: dev → stage → prod
- Prioritize Terraform core and provider updates
Minor versions:
- Regular maintenance (monthly/quarterly)
- Review changelog for breaking changes
- Test thoroughly before production
Major versions:
- Planned upgrade cycles
- Dedicated testing period
- May require code changes
- Phased rollout: dev → stage → prod
---
Refactoring Quick Reference
Common Refactoring Patterns
Pattern 1: Count to For_Each Migration
When: Need stable resource addressing or items might be reordered
# Step 1: Add for_each, keep count commented
# Step 2: Add moved blocks for each resource
# Step 3: Run terraform plan (should show "moved" not "destroy/create")
# Step 4: Apply changes
# Step 5: Remove commented countKey principle: Use moved blocks to preserve existing resources
Pattern 2: Legacy to Modern Terraform
0.12/0.13 → 1.x checklist:
- [ ] Replace
element(concat(...))→try() - [ ] Add
nullable = falsewhere appropriate - [ ] Use
optional()in object types (1.3+) - [ ] Add
validationblocks - [ ] Migrate secrets to write-only arguments (1.11+)
- [ ] Use
movedblocks for refactoring (1.1+) - [ ] Add cross-variable validation (1.9+)
Pattern 3: Secrets Remediation
Goal: Move secrets out of Terraform state
# Step 1: Create secret in AWS Secrets Manager (outside Terraform)
aws secretsmanager create-secret --name prod-db-password --secret-string "..."
# Step 2: Update Terraform to use data sources
# Step 3: Use write-only argument (Terraform 1.11+)
# Step 4: Remove random_password resource or variable
# Step 5: Apply and verify secret not in state
terraform show | grep -i password # Should not appearRefactoring Decision Tree
What are you refactoring?
├─ Resource addressing (count[0] → for_each["key"])
│ └─ Use: moved blocks + for_each conversion
│
├─ Secrets in state
│ └─ Use: AWS Secrets Manager + write-only arguments (1.11+)
│
├─ Legacy Terraform syntax (0.12/0.13)
│ └─ Use: Modern feature checklist above
│
└─ Module structure (rename, reorganize)
└─ Use: moved blocks to preserve resourcesMigration Best Practices
Before refactoring: 1. Backup state file 2. Test in development first 3. Review terraform plan carefully 4. Document what changed and why
During refactoring: 1. One change at a time 2. Verify each step with terraform plan 3. Use moved blocks, not destroy/recreate 4. Keep git history clean with logical commits
After refactoring: 1. Verify idempotency (plan shows no changes) 2. Test in staging before production 3. Update documentation 4. Communicate changes to team
For detailed refactoring patterns, see: Code Patterns: Refactoring Patterns
---
Common Patterns
Resource Naming
# ✅ Good: Descriptive, contextual
resource "aws_instance" "web_server" { }
resource "aws_s3_bucket" "application_logs" { }
# ❌ Bad: Generic
resource "aws_instance" "main" { }
resource "aws_s3_bucket" "bucket" { }Variable Naming
# ✅ Good: Context-specific
var.vpc_cidr_block
var.database_instance_class
# ❌ Bad: Generic
var.cidr
var.instance_classFile Organization
Standard module structure:
├── main.tf # Primary resources
├── variables.tf # Input variables
├── outputs.tf # Output values
├── versions.tf # Provider versions
└── README.md # Documentation---
Back to: Main Skill File
Testing Frameworks - Detailed Guide
Part of: terraform-skill
Purpose: Detailed guides for Terraform/OpenTofu testing frameworks
This document provides in-depth guidance on testing frameworks for Infrastructure as Code. For the decision matrix and high-level overview, see the main skill file.
---
Table of Contents
1. Static Analysis 2. Plan Testing 3. Native Terraform Tests 4. Terratest (Go-based)
---
Static Analysis
Always do this first. Zero cost, catches 40%+ of issues before deployment.
Pre-commit Hooks
# In .pre-commit-config.yaml
- repo: https://github.com/antonbabenko/pre-commit-terraform
hooks:
- id: terraform_fmt
- id: terraform_validate
- id: terraform_tflintWhat Each Tool Checks
- `terraform fmt` - Code formatting consistency
- `terraform validate` - Syntax and internal consistency
- `TFLint` - Best practices, provider-specific rules
- `trivy` / `checkov` - Security vulnerabilities
When to Use
Every commit, always. Zero cost, catches 40%+ of issues.
---
Plan Testing
What terraform plan Validates
- Verify expected resources will be created/modified/destroyed
- Catch provider authentication issues
- Validate variable combinations
- Review before applying
In CI/CD
terraform init
terraform plan -out=tfplan
# Optionally: Convert plan to JSON and validate with tools
terraform show -json tfplan | jq '.'Limitations
- Doesn't deploy real infrastructure
- Can't catch runtime issues (IAM permissions, network connectivity)
- Won't find resource-specific bugs
---
Native Terraform Tests
Available: Terraform 1.6+, OpenTofu 1.6+
When to Use
- Team primarily works in HCL (no Go/Ruby experience needed)
- Testing logical operations and module behavior
- Want to avoid external testing dependencies
Basic Structure
Test discovery:terraform testfinds*.tftest.hclfiles undertests/relative to the module root. Use-filter=<path>to scope to a specific file.
# tests/s3_bucket.tftest.hcl
run "create_bucket" {
command = apply
assert {
condition = aws_s3_bucket.main.bucket != ""
error_message = "S3 bucket name must be set"
}
}
run "verify_encryption" {
command = apply # `rule` is a set; use `one(...)` to extract the singleton
assert {
condition = one(aws_s3_bucket_server_side_encryption_configuration.main.rule).apply_server_side_encryption_by_default[0].sse_algorithm == "AES256"
error_message = "Bucket must use AES256 encryption"
}
}Pattern applies identically on Azure/GCP; only provider/resource names change. See Module Patterns: Cross-cloud resource map.
Critical: Validate Resource Schemas First
Always use Terraform MCP to validate resource schemas before writing tests:
# Example workflow in Claude Code:
# 1. Search for provider documentation
mcp__terraform__search_providers({
provider_name: "aws",
provider_namespace: "hashicorp",
service_slug: "s3_bucket_server_side_encryption_configuration",
provider_document_type: "resources"
})
# 2. Get detailed schema
mcp__terraform__get_provider_details({
provider_doc_id: "12345" # from search results
})Block-type distinctions the LLM must verify against the real schema:
- set — unordered, cannot index with
[0] - list — ordered, indexable
- computed attribute — only known after apply
Common Schema Patterns:
| AWS Resource | Block Type | Indexing |
|---|---|---|
rule in aws_s3_bucket_server_side_encryption_configuration | set | ❌ Cannot use [0] |
transition in aws_s3_bucket_lifecycle_configuration | set | ❌ Cannot use [0] |
noncurrent_version_expiration in lifecycle | nested block (MaxItems=1) — list-of-1 | ✅ Can use [0] |
Working with Set-Type Blocks
Problem: Cannot index sets with [0]
# ❌ WRONG: This will fail
condition = aws_s3_bucket_server_side_encryption_configuration.this.rule[0].bucket_key_enabled == true
# Error: Cannot index a set valueSolution 1: Use command = apply to materialize the set
run "test_encryption" {
command = apply # Creates real/mocked resources
assert {
# Now the set is materialized and can be checked
condition = length([for rule in aws_s3_bucket_server_side_encryption_configuration.this.rule :
rule.bucket_key_enabled if rule.bucket_key_enabled == true]) > 0
error_message = "Bucket key should be enabled"
}
}Solution 2: Check at resource level (avoid accessing nested blocks)
run "test_encryption_exists" {
command = plan
assert {
# Check that the resource exists without accessing set members
condition = aws_s3_bucket_server_side_encryption_configuration.this != null
error_message = "Encryption configuration should be created"
}
}Solution 3: Use for expressions (works in apply mode)
run "test_encryption_algorithm" {
command = apply
assert {
condition = alltrue([
for rule in aws_s3_bucket_server_side_encryption_configuration.this.rule :
alltrue([
for config in rule.apply_server_side_encryption_by_default :
config.sse_algorithm == "AES256"
])
])
error_message = "Encryption should use AES256"
}
}command = plan vs command = apply
| Goal | Mode | Why |
|---|---|---|
Input-derived attribute (bucket name from var.bucket) | plan | value known before refresh |
| Variable default / validation | plan | fast, no resource creation |
| Computed attribute (ARN, generated name, cloud ID) | apply | only known after provider round-trip |
| Set-type nested block | apply | materializes the set so for expressions resolve |
| Real behavior / mocked provider responses | apply | runs the actual create path |
# ✅ plan — input-derived
run "test_input" {
command = plan
variables { bucket = "test-bucket" }
assert {
condition = aws_s3_bucket.this.bucket == "test-bucket"
error_message = "Bucket name should match input"
}
}
# ✅ apply — computed
run "test_prefix" {
command = apply
variables { bucket_prefix = "test-" }
assert {
condition = startswith(aws_s3_bucket.this.bucket, "test-")
error_message = "Bucket name should start with prefix"
}
}❌ Asserting a computed value in plan mode → Condition expression could not be evaluated at this time. Fix: switch the run block to command = apply, or assert a different attribute that is known at plan.
With Mocking (1.7+)
mock_provider "aws" {
mock_resource "aws_instance" {
defaults = {
id = "i-mock123"
arn = "arn:aws:ec2:us-east-1:123456789:instance/i-mock123"
}
}
}Pros
- Native HCL syntax (familiar to Terraform users)
- No external dependencies
- Fast execution with mocks
- Good for unit testing module logic
Cons
- Newer feature (less mature than Terratest)
- Limited ecosystem/examples
- Mocking doesn't catch real-world AWS behavior
---
Complete Test Examples (Following Best Practices)
Example 1: S3 Bucket Tests
# tests/unit/s3_bucket.tftest.hcl
mock_provider "aws" {} # Zero cost with mocks
# Test 1: Input validation (fast, plan mode)
run "validate_bucket_name" {
command = plan
variables {
bucket = "my-test-bucket"
}
assert {
condition = aws_s3_bucket.this.bucket == "my-test-bucket"
error_message = "Bucket name should match input"
}
}
# Test 2: Encryption defaults (apply mode for set access)
run "verify_default_encryption" {
command = apply
variables {
bucket = "encrypted-bucket"
}
assert {
# Using for expression to check set-type block
condition = alltrue([
for rule in aws_s3_bucket_server_side_encryption_configuration.this.rule :
alltrue([
for config in rule.apply_server_side_encryption_by_default :
config.sse_algorithm == "AES256"
])
])
error_message = "Default encryption should be AES256"
}
assert {
# Check bucket key at rule level
condition = alltrue([
for rule in aws_s3_bucket_server_side_encryption_configuration.this.rule :
rule.bucket_key_enabled == true
])
error_message = "Bucket key should be enabled"
}
}
# Test 3: Computed values (apply mode required)
run "verify_generated_name" {
command = apply
variables {
bucket_prefix = "test-"
}
assert {
condition = startswith(aws_s3_bucket.this.bucket, "test-")
error_message = "Generated bucket name should have prefix"
}
assert {
condition = length(aws_s3_bucket.this.bucket) > 5
error_message = "Bucket name should be generated"
}
}Example 2: Lifecycle Rules
# tests/unit/lifecycle.tftest.hcl
mock_provider "aws" {}
run "verify_lifecycle_transitions" {
command = apply # Required for set-type transition blocks
variables {
bucket = "lifecycle-bucket"
lifecycle_rules = [{
id = "archive"
enabled = true
transition = [
{ days = 90, storage_class = "GLACIER" },
{ days = 180, storage_class = "DEEP_ARCHIVE" }
]
}]
}
assert {
# Check that both transitions exist using for expression
condition = length([
for rule in aws_s3_bucket_lifecycle_configuration.this.rule :
rule.id if rule.id == "archive"
]) == 1
error_message = "Lifecycle rule should exist"
}
assert {
# Verify transition count using length
condition = alltrue([
for rule in aws_s3_bucket_lifecycle_configuration.this.rule :
length(rule.transition) == 2
])
error_message = "Should have 2 transitions"
}
}---
Terratest (Go-based)
Recommended for: Teams with Go experience, robust integration testing
When to Use
- Team has Go experience
- Need robust integration testing
- Testing multiple providers/complex infrastructure
- Want battle-tested framework with large community
Basic Structure
package test
import (
"testing"
"github.com/gruntwork-io/terratest/modules/random"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/stretchr/testify/assert"
)
func TestS3Module(t *testing.T) {
t.Parallel() // ALWAYS include for parallel execution
terraformOptions := &terraform.Options{
TerraformDir: "../examples/complete",
Vars: map[string]interface{}{
"bucket_name": "test-bucket-" + random.UniqueId(),
},
}
// Clean up resources after test
defer terraform.Destroy(t, terraformOptions)
// Run terraform init and apply
terraform.InitAndApply(t, terraformOptions)
// Get outputs and verify
bucketName := terraform.Output(t, terraformOptions, "bucket_name")
assert.NotEmpty(t, bucketName)
}Cost Management
// Use tags for automated cleanup
Vars: map[string]interface{}{
"tags": map[string]string{
"Environment": "test",
"TTL": "2h", // Auto-delete after 2 hours
},
}Critical Patterns
1. Always use `t.Parallel()` - Enables parallel test execution 2. Always use `defer terraform.Destroy()` - Ensures cleanup 3. Use unique identifiers - Avoid resource conflicts 4. Tag resources - Enable cost tracking and automated cleanup 5. Use separate AWS accounts - Isolate test infrastructure
Real-world Costs
- Small module (S3, IAM): $0-5 per run
- Medium module (VPC, EC2): $5-20 per run
- Large module (RDS, ECS cluster): $20-100 per run
Optimization with Test Stages
// Test stages for faster iteration
stage := test_structure.RunTestStage
stage(t, "setup", func() {
terraform.InitAndApply(t, opts)
})
stage(t, "validate", func() {
// Assertions here
})
stage(t, "teardown", func() {
terraform.Destroy(t, opts)
})
// Skip stages during development:
// export SKIP_setup=true
// export SKIP_teardown=true---
Best Practices Summary
For All Frameworks
1. Start with static analysis - Always free, always fast 2. Use unique identifiers - Prevent resource conflicts 3. Tag test resources - Enable tracking and cleanup 4. Separate test accounts - Isolate test infrastructure 5. Implement TTL - Automatic resource cleanup
Framework Selection
Quick syntax check? → terraform validate + fmt
Security scan? → trivy + checkov
Terraform 1.6+, simple logic? → Native tests
Complex integration or multi-cloud orchestration? → TerratestCost Optimization
1. Use mocking for unit tests 2. Implement resource TTL tags 3. Run integration tests only on main branch 4. Use smaller instance types in tests 5. Share test resources when safe
---
LLM Mistake Checklist — Testing
Common model mistakes when generating test code:
- asserts computed values (ARNs, generated names, cloud-assigned IDs) in
command = planmode — must usecommand = apply - indexes set-type nested blocks with
[0]— sets are unordered, useforexpressions orcommand = applyto materialize - treats mocked-provider tests as integration coverage — mocks validate logic only, not provider behavior
- forgets to exercise
validationblocks with invalid inputs — only tests the happy path - skips idempotency (
terraform plan -detailed-exitcodeafter apply) — the most common regression detector - asserts on Terraform syntax instead of module behavior (
terraform validatealready covers syntax) - runs expensive real-cloud integration tests on every commit instead of gating them behind main/scheduled
- omits cleanup, leaving orphaned resources billed against the test account
---
Back to: Main Skill File
Related skills
Forks & variants (1)
Terraform Skill has 1 known copy in the catalog totaling 4 installs. They canonicalize to this original listing.
- aws-samples - 4 installs
How it compares
terraform-skill is an agent skill for write, review, and debug terraform or opentofu modules, tests, ci scans, and state operations, not a generic alternative.
FAQ
Who is terraform-skill for?
Developers using Cloud & Infrastructure workflows with agent-guided SKILL.md steps.
When should I use terraform-skill?
Write, review, and debug Terraform or OpenTofu modules, tests, CI scans, and state operations.
Is terraform-skill safe to install?
Review the Security Audits panel on this page before installing in production.