Terraform Skill
Anton BabenkoCommunityCreated by Anton Babenko
- Skill
- Tool integration
- Cloud and DevOps
- Apache-2.0
- Medium risk
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured workflow for managing Terraform and OpenTofu configurations. It emphasizes a diagnose-before-generate approach, requiring explicit context such as runtime versions, provider details, and environment criticality. It includes a response contract to ensure risk-aware planning, validation, and rollback procedures, while offering specific guidance on module hierarchy, state management, security, and testing strategies.
What it does
- Diagnoses infrastructure failure modes like identity churn, state corruption, and secret exposure.
- Enforces a response contract requiring version floors, risk assessment, and validation plans.
- Provides patterns for module development, directory layout, and naming conventions.
- Offers guidance on CI/CD pipeline stages, including plan artifact review and drift prevention.
- Facilitates safe state management, including backend selection and locking protocols.
- Supports semantic code navigation using terraform-ls or fallback search tools.
When to use it
- When writing or reviewing Terraform/OpenTofu modules and configurations.
- When debugging CI/CD pipeline failures or infrastructure drift.
- When planning complex refactors or state migrations.
- When configuring remote state backends or implementing security compliance checks.
Advantages
- Reduces risk of destructive changes through mandatory plan-destroy protocols.
- Improves code maintainability via standardized module and variable contracts.
- Ensures consistent security practices through integrated policy and secret handling.
- Provides clear version-aware guidance to prevent common configuration errors.
Usage examples
- “I am refactoring a module and worried about resource identity churn. How should I proceed?”
- The agent will guide you through using 'moved' blocks, comparing 'count' vs 'for_each' patterns, and validating the plan to ensure no unexpected resource destruction occurs.
- “How do I securely manage secrets in my Terraform configuration?”
- The agent will advise on using cloud-native secret managers, 'sensitive' variable flags, or 'write_only' arguments, and will check your implementation against security best practices.
- “Help me set up a CI/CD pipeline for my infrastructure.”
- The agent will provide a structured pipeline template including validation, testing, plan artifact generation, and environment-protected apply stages.
- “My state file is locked and I cannot run any operations. What should I do?”
- The agent will diagnose the state backend, verify locking mechanisms, and provide recovery steps based on your specific provider and backend configuration.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/antonbabenko/terraform-skill/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip terraform-skill.zip -d .agents/skills
Documentation by Anton Babenko
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:
Assumptions & version floor — runtime (
terraformortofu), exact version, providers, state backend, execution path (local/CI/Cloud/Atlantis), environment criticality. State assumptions explicitly if the user did not provide them.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.
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.
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
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.
Load only the matching reference file(s) — do not preload depth the task does not need.
Propose fix with risk controls — why this addresses the mode, what could still go wrong, guardrails (tests/approvals/rollback).
Generate artifacts — HCL, migration blocks (
moved,import), CI changes, policy rules.Validate before finalizing — run validation commands tailored to risk tier.
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 onlyPrefix 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 blocksSet-type blocks cannot be indexed with
[0]— useforexpressions or materialize viacommand = applyCommon 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 checklistCI/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, localsCode 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
Files
- ATTRIBUTION.mdAdded by AutoGineer946 B
- LICENSELicence file added by AutoGineer10.6 KiB
- SKILL.md19.9 KiB
- references/ci-cd-workflows.md13.8 KiB
- references/code-intelligence-lsp.md6.6 KiB
- references/code-patterns.md30.9 KiB
- references/module-patterns.md22.9 KiB
- references/quick-reference.md19.4 KiB
- references/security-compliance.md18.6 KiB
- references/state-management.md45.1 KiB
- references/testing-frameworks.md13.7 KiB
references/quick-reference.md
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
Command Cheat Sheet
Decision Flowchart
Version-Specific Guidance
Troubleshooting Guide
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.hclDecision 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 changesVersion-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:
Different Terraform/provider versions
Different environment variables
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:
Use mocking for unit tests (Terraform 1.7+)
mock_provider "aws" { ... }Implement resource TTL tags
Vars: map[string]interface{}{ "tags": map[string]string{ "Environment": "test", "TTL": "2h", }, }Run integration tests only on main branch
if: github.ref == 'refs/heads/main'Use smaller instance types
instance_type = "t3.micro" # Not "m5.large"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:
Terraform process crashed or was killed
Network interruption during operation
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-statefailsBackend 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.jsonMigration 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
Keep Terratest for:
Complex integration tests
Multi-step workflows
Cross-provider tests
Migrate to native tests:
Simple unit tests
Logic validation
Mock-friendly tests
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.
HCL ≤1.5.x — no code changes; providers and state files compatible. Verify post-1.6 features per version.
CI/CD — swap
terraformfortofuininit/plan/applyinvocations.Docs — note OpenTofu compatibility in README; update workflow templates to the
tofubinary.
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:
Backup state file
Test in development first
Review terraform plan carefully
Document what changed and why
During refactoring:
One change at a time
Verify each step with terraform plan
Use moved blocks, not destroy/recreate
Keep git history clean with logical commits
After refactoring:
Verify idempotency (plan shows no changes)
Test in staging before production
Update documentation
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 # DocumentationBack to: Main Skill File
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
What our scanner noticed· Medium risk
- Instructions that use the network
- Downloads piped into a shell
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- Anton Babenko
- Publisher
- Anton Babenko (Community)
- Source
- antonbabenko/terraform-skill · skills/terraform-skill · commit 9c1e92d
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Anton Babenko or Anton Babenko.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download terraform-skill.zip