Generated banner for Terraform Skill
Generated logo for Terraform Skill

Terraform Skill

Anton BabenkoCommunityCreated by Anton Babenko

  • Skill
  • Tool integration
  • Cloud and DevOps
  • Apache-2.0
  • Medium risk

From the author

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.
— the description by Anton Babenko

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

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/antonbabenko/terraform-skill/download
  2. Unzip 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:

  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 categorySymptomsPrimary references
Identity churnResource addresses shift after refactor, count index churn, missing moved blocksCode Patterns: count vs for_each, Code Patterns: moved blocks, Code Patterns: LLM mistakes
Secret exposureSecrets in defaults, state, logs, CI artifactsSecurity & Compliance, Code Patterns: write-only, State Management
Blast radiusOversized stacks, shared prod/non-prod state, unsafe appliesState Management, Module Patterns
Destroy cascadeTargeted destroy deletes more than expected; locals referencing a targeted resource make all for_each consumers implicit dependentsResponse Contract: plan-destroy first; State Management: Safe Destroy
CI driftLocal plan ≠ CI plan, apply without reviewed artifact, unpinned versionsCI/CD Workflows, Code Patterns: versions
Compliance gapsMissing policy stage, no approval model, no evidence retentionSecurity & Compliance, CI/CD Workflows
Testing blind spotsPlan-only validation of computed values, set-type indexing, mock/real confusionTesting Frameworks
State corruption / recoveryStuck lock, backend migration, drift reconciliationState Management
Provider upgrade riskBreaking-change provider bump, unpinned modulesCode Patterns: versions, Module Patterns
Provider lifecycleRemoving a provider with resources still in state, orphaned resources, removed block usageState Management: Provider Removal
Bootstrap / orchestration misusenull_resource + local-exec for bootstrap, remote-exec for setup scripts, provisioner stdout leaking secrets in CI logsCode Patterns: Provisioners as Last Resort
Navigation / safe-rename blind spotsCannot locate symbol defs/refs semantically, value-symbol rename done as blind text replace, grep-only refactor missing refs, hallucinated rg shimCode Intelligence
Cross-cloud / provider mapping"What's the Azure/GCP equivalent of X", picking a backend/auth model per cloudState 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
TypeWhen to UseScope
Resource moduleSingle logical group of connected resourcesVPC + subnets, SG + rules
Infrastructure moduleCollection of resource modules for a purposeMultiple resource modules in one region/account
CompositionComplete infrastructureSpans 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 fixtures

Separate 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, not aws_instance.main)

  • Reserve this for genuine singleton resources only

  • Prefix variables with context (vpc_cidr_block, not cidr)

  • 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?
SituationApproachToolsCost
Quick syntax checkStatic analysisvalidate, fmtFree
Pre-commit validationStatic + lintvalidate, tflint, trivy, checkovFree
Terraform 1.6+, simple logicNative test frameworkterraform testFree-Low
Pre-1.6, or Go expertiseIntegration testingTerratestLow-Med
Security/compliance focusPolicy as codeOPA, SentinelFree
Cost-sensitive workflowMock providers (1.7+)Native tests + mocksFree
Multi-cloud, complexFull integrationTerratest + real infraMed-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 only

  • command = apply — required for computed values (ARNs, generated names) and set-type nested blocks

  • Set-type blocks cannot be indexed with [0] — use for expressions or materialize via command = 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

ScenarioUseWhy
Boolean condition (create / don't)count = condition ? 1 : 0Optional singleton toggle
Items may be reordered or removedfor_each = toset(list)Stable resource addresses
Reference by keyfor_each = mapNamed access
Multiple named resourcesfor_eachBetter 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 Terratest

Variable 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
PatternUse WhenExample Path
Per environmentDifferent teams per envprod/terraform.tfstate, staging/...
Per componentIndependent lifecyclesprod/vpc/, prod/eks/, prod/rds/
Hybrid (recommended)Both benefitsprod/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

ComponentStrategyExample
Terraform runtimePin minorrequired_version = "~> 1.9"
ProvidersPin majorversion = "~> 5.0"
Modules (prod)Pin exactversion = "5.1.2"
Modules (dev)Allow patchversion = "~> 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+)

FeatureMin versionCommon use
try()0.13+Safe fallbacks, replaces element(concat())
nullable = false1.1+Prevent null silently overriding defaults
moved blocks1.1+Refactor without destroy/recreate
optional() with defaults1.3+Typed object attributes
import blocks1.5+Declarative imports, reviewable in VCS
check blocks1.5+Runtime assertions
Native terraform test1.6+Built-in test framework
Mock providers1.7+Cost-free unit testing
removed blocks1.7+Declarative resource removal
Provider-defined functions1.8+Provider-specific transformations (requires provider to declare functions)
Cross-variable validation1.9+Reference other var.* in validation blocks
write_only arguments1.11+Secrets never stored in state
S3 native lock-file1.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 test available — 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_only arguments 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.

GoalUseTradeoff
Find definition / all referencesterraform-ls goToDefinition / findReferencesNeeds init + a position anchor
Rename value symbol (var/local/output/provider alias)Manual: findReferences -> per-file fresh Read -> edit -> validateNo rename provider
Rename resource/module addressmoved block + plan shows 0 destroyText rename forces destroy/recreate
Exact text / known name / .tfvars / non-HCLrg + ReadNo 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/tofu on PATH, terraform init run; cold start may need one retry.

  • ✅ LSP calls are position-anchored (file:line:character) - anchor with rg first, 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_state rules, 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_each deep 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

Files

references/testing-frameworks.md

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_tflint
What 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 test finds *.tftest.hcl files under tests/ 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 ResourceBlock TypeIndexing
rule in aws_s3_bucket_server_side_encryption_configurationset❌ Cannot use [0]
transition in aws_s3_bucket_lifecycle_configurationset❌ Cannot use [0]
noncurrent_version_expiration in lifecyclenested 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 value

Solution 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
GoalModeWhy
Input-derived attribute (bucket name from var.bucket)planvalue known before refresh
Variable default / validationplanfast, no resource creation
Computed attribute (ARN, generated name, cloud ID)applyonly known after provider round-trip
Set-type nested blockapplymaterializes the set so for expressions resolve
Real behavior / mocked provider responsesapplyruns 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? → Terratest
Cost 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 = plan mode — must use command = apply

  • indexes set-type nested blocks with [0] — sets are unordered, use for expressions or command = apply to materialize

  • treats mocked-provider tests as integration coverage — mocks validate logic only, not provider behavior

  • forgets to exercise validation blocks with invalid inputs — only tests the happy path

  • skips idempotency (terraform plan -detailed-exitcode after apply) — the most common regression detector

  • asserts on Terraform syntax instead of module behavior (terraform validate already 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

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.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download terraform-skill.zip