SkillAtlasSkill 详情

terraform-skill

A best-practices skill for Terraform and OpenTofu, for AI coding agents (Claude Code, Cursor, Co...

审核状态:已审核Quality 72Security 70

复制安装命令

用 Codex 或 Claude 安装复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它先审查 Skill 页面再帮你安装。

复制前请先查看来源、License 和安全提示。

项目 README

来源文件:README.md

抓取于 2026年8月16日

Terraform & OpenTofu Skill for AI Agents

Agent Skill Terraform OpenTofu License

A best-practices skill for Terraform and OpenTofu, for AI coding agents (Claude Code, Cursor, Copilot, Gemini CLI, OpenCode, Codex, Kiro, and more). It helps the agent test code, structure modules, set up CI/CD, and write production infrastructure code.

AWS, Azure, and GCP are all first-class. AWS stays the default in examples, but the same backend, auth, security, and resource guidance applies to all three - ask for the Azure or GCP equivalent of any pattern and the skill maps it.

What this skill provides

Testing frameworks

  • Decision matrix for native tests vs Terratest
  • Testing workflows (static, integration, E2E)
  • Examples and patterns

Module development

  • Structure and naming conventions
  • Versioning strategies
  • Public vs private module patterns

State management

  • Remote backends (S3, Azure, GCS, Terraform Cloud)
  • Locking and security
  • Multi-team state isolation
  • Migration and recovery procedures

CI/CD integration

  • GitHub Actions workflows
  • GitLab CI examples
  • Cost optimization
  • Compliance automation

Security and compliance

  • Trivy and Checkov integration
  • Policy-as-code patterns
  • Compliance scanning workflows

Quick reference

  • Decision flowcharts
  • Common patterns (DO vs DON'T)
  • Cheat sheets

Installation

Installed through one Claude Code marketplace, antonbabenko/agent-plugins (terraform-skill is listed there as an external plugin). Do not also add antonbabenko/terraform-skill as a marketplace - both use the same marketplace name and will clash.

Quick install (any agent)

Works with any Agent Skills-compatible tool:

npx skills add https://github.com/antonbabenko/terraform-skill

Per-host instructions

Claude Code
/plugin marketplace add antonbabenko/agent-plugins
/plugin install terraform-skill@antonbabenko
Gemini CLI
gemini extensions install https://github.com/antonbabenko/terraform-skill

Update with gemini extensions update terraform-skill.

Cursor
git clone https://github.com/antonbabenko/terraform-skill.git ~/.cursor/skills/terraform-skill

Cursor auto-discovers skills from .agents/skills/ and .cursor/skills/.

Copilot
/plugin install https://github.com/antonbabenko/terraform-skill
# or
git clone https://github.com/antonbabenko/terraform-skill.git ~/.copilot/skills/terraform-skill

Copilot auto-discovers skills from .copilot/skills/.

OpenCode
git clone https://github.com/antonbabenko/terraform-skill.git ~/.agents/skills/terraform-skill

OpenCode auto-discovers skills from .agents/skills/, .opencode/skills/, and .claude/skills/.

Codex (OpenAI)
git clone https://github.com/antonbabenko/terraform-skill.git ~/.agents/skills/terraform-skill

Codex auto-discovers skills from ~/.agents/skills/ and .agents/skills/. Update with cd ~/.agents/skills/terraform-skill && git pull.

For a managed Codex plugin install, use the antonbabenko/agent-plugins marketplace (codex plugin marketplace add antonbabenko/agent-plugins, then install terraform-skill). Do not add antonbabenko/terraform-skill as a separate marketplace - it clashes by name with agent-plugins.

Autohand Code

Install the skill globally:

git clone https://github.com/antonbabenko/terraform-skill.git
mkdir -p ~/.autohand/skills
cp -R terraform-skill/skills/terraform-skill ~/.autohand/skills/

Or install it only for the current project:

git clone https://github.com/antonbabenko/terraform-skill.git
mkdir -p .autohand/skills
cp -R terraform-skill/skills/terraform-skill .autohand/skills/

Autohand Code discovers skills from ~/.autohand/skills/ and .autohand/skills/.

Kiro
git clone https://github.com/antonbabenko/terraform-skill.git ~/.kiro/skills/terraform-skill

Kiro auto-discovers skills from .kiro/skills/ (workspace) and ~/.kiro/skills/ (global).

Antigravity/Antigravity IDE/Antigravity CLI
git clone https://github.com/antonbabenko/terraform-skill.git
ln -s "$(pwd)/terraform-skill/skills/terraform-skill" ~/.gemini/config/skills/terraform-skill

Update with git pull.

Kiro

This repo is also a Kiro Power (root POWER.md + optional mcp.json). In Kiro: Powers panel → "Add power from GitHub", then paste:

https://github.com/antonbabenko/terraform-skill

Kiro activates the power on keyword match (e.g. "terraform", "opentofu", "state", "modules"). Installing it also registers the optional read-only HashiCorp terraform-mcp-server (from mcp.json) under the Powers section of ~/.kiro/settings/mcp.json — the guidance works without it. POWER.md is generated from skills/terraform-skill/SKILL.md; the skill content is shared, not duplicated.

Manual (symlink local clone)
git clone https://github.com/antonbabenko/terraform-skill
mkdir -p ~/.claude/plugins
ln -s "$(pwd)/terraform-skill" ~/.claude/plugins/terraform-skill

Claude Code autodiscovers the skill at skills/terraform-skill/SKILL.md on next launch. Edits to the clone are picked up live.

Verify installation

After installation, try:

"Create a Terraform module with testing for an S3 bucket"

Claude picks up the skill automatically when working with Terraform or OpenTofu code.

Recommended companion: code-intelligence

Install the code-intelligence plugin alongside this one:

/plugin marketplace add antonbabenko/agent-plugins
/plugin install code-intelligence@antonbabenko

It holds the general, any-language rules for navigating code (when to use a language server, plain text search, or fuzzy search; how to anchor a lookup to a position; what to do when a tool fails; saying so when one tool is swapped for another). terraform-skill is the Terraform-specific version of those rules. Why install it:

  • Fewer tokens - the rules live in one place. The agent loads them when needed instead of repeating them in every language skill.
  • More accurate - it finds definitions and references by meaning, not by plain text matching, so renames and refactors do not miss spots or change the wrong ones.
  • Faster - it picks the right tool the first time instead of retrying, and says up front when it had to use a different one.

terraform-skill works on its own without it. The name code-intelligence is not unique; if a code-intelligence skill is active, check it is the one from antonbabenko/agent-plugins.

Quick start examples

Create a module with tests (AWS / Azure / GCP):

"Create a Terraform module for an AWS VPC with native tests"

"Build an Azure module: VNet, subnets, and a PostgreSQL Flexible Server, with native tests"

"Write a GCP module for a VPC network, subnetwork, and Cloud SQL Postgres, with native tests"

Set up remote state:

"Configure an S3 backend with native use_lockfile locking and encryption for Terraform state"

"Choose and configure a remote state backend for AWS, Azure, or GCP (locking, encryption, versioning)"

Review existing code:

"Review this Terraform configuration following best practices"

Generate CI/CD workflow:

"Create a GitHub Actions workflow for Terraform with cost estimation"

Testing strategy:

"Help me choose between native tests and Terratest for my modules"

State management:

"How should I organize state files for a multi-team environment?"

Longer example prompts

These assume a recent Terraform/OpenTofu - use_lockfile is 1.10+, write_only is 1.11+.

AWS: production service (modules + composition, OIDC, native locking)

"I'm building a new production service on AWS. Design reusable Terraform modules plus a prod/staging composition for a VPC with public/private subnets across 3 AZs, an ECS Fargate service behind an ALB, and an RDS Postgres instance. Include native terraform test coverage, variables with descriptions/types/validation, S3 remote state with encryption, bucket versioning, and native use_lockfile locking (Terraform 1.10+). Keep secret values out of plan/state - use write_only / *_wo arguments where the provider supports them (Terraform 1.11+) and Secrets Manager/SSM references for runtime secrets. Add a GitHub Actions workflow that runs fmt/validate/tflint/trivy on PRs, produces a reviewed plan artifact, and applies it via AWS OIDC (no static keys). Keep prod/staging state isolated and follow naming conventions."

GCP: port the AWS pattern (cross-cloud mapping, WIF, gcs backend)

"We're standardizing IaC across clouds. Port our AWS module pattern to GCP: reusable modules plus an environment composition for a VPC network, a regional subnetwork, and a Cloud SQL Postgres instance (google_sql_database_instance). Use the gcs backend (bucket + prefix) for remote state, and show the state bootstrap bucket separately with object versioning, uniform bucket-level access, public access prevention, and IAM bindings. Use Workload Identity Federation for keyless GitHub Actions auth (no long-lived service-account keys) and native tests. Also show the cross-cloud equivalents (resources + backend) so the team sees the AWS-to-GCP mapping."

What it covers

Testing strategy

Decision matrices for native tests (Terraform 1.6+) vs Terratest (Go-based), plus multi-environment testing patterns.

Module development

Naming conventions (terraform-<PROVIDER>-<NAME>), directory structure, input/output design, version constraints, and documentation standards.

CI/CD workflows

GitHub Actions, GitLab CI, Atlantis, Infracost cost estimation, Trivy/Checkov scanning, and compliance checks.

Security and compliance

Static analysis, policy-as-code, secrets management, state file security, backend encryption, and compliance scanning workflows.

Patterns and anti-patterns

Side-by-side DO vs DON'T examples for variable naming, resource naming, module composition, state management, and provider configuration.

Why this skill

This skill started from field-tested Terraform and OpenTofu patterns, then grew through contributions from people who hit missing guidance and added it back.

Sources:

Version-specific guidance:

  • Terraform 1.0+ features
  • OpenTofu 1.6+ compatibility
  • Native test framework (1.6+)
  • Current tooling ecosystem (2024-2026)

Decision frameworks: not just "what to do" but "when and why".

Requirements

  • An AI agent with skill support: Claude Code, Cursor, Copilot, Gemini CLI, OpenCode, Codex, Kiro, or any Agent Skills-compatible host
  • Terraform 1.0+ or OpenTofu 1.6+
  • Optional: Terraform MCP server for registry integration

Code intelligence (optional)

The skill works without a language server. To jump to a definition, find references, outline a file, or show hover docs, it can also use terraform-ls, HashiCorp's official Terraform language server.

  • Optional. Without terraform-ls the skill falls back to text search (rg) plus reading files. Nothing breaks; you get text matches instead of matches by meaning.
  • Needs. A local terraform (or tofu) binary on PATH, and terraform init run in the workspace, before it can resolve names across modules and providers.
  • Install. Get it from the terraform-ls releases page, or turn it on through your editor or agent host. Use whatever version your host supports.
    • Claude Code: install it as an LSP plugin - /plugin marketplace add boostvolt/claude-code-lsps then /plugin install terraform-ls@claude-code-lsps.

How the skill uses it:

  • Use the language server to follow a name to where it is defined or used; use rg plus reading files for exact text, known names, .tfvars, comments, and non-HCL files.
  • Point the language server at a spot in the file first (find an occurrence, then ask about that position).
  • terraform-ls cannot rename for you. To rename a variable, local, or output: find every reference, then edit each by hand. To rename a resource or module address: use a moved block, not a text replace.

Contributing

See CLAUDE.md for skill development guidelines, content structure, how to propose improvements, and the validation approach.

Report bugs or request features via GitHub Issues.

Related resources

Official documentation

Community resources

Development tools

License

Apache 2.0

Agent / MCP / Skill 创作测试与质量DevOps 与部署内容与创作

中风险

  • 来源需自行核对维护者身份。
  • 包含脚本或命令调用,安装前请复核。
  • 可能需要外部 token、网络权限或第三方服务。
  • 未检测到高风险命令。
  • 扫描发现:1 条。

Codex — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/antonbabenko/terraform-skill.git
  3. 将 "skills/terraform-skill" 文件夹复制到 Codex 的 skills 目录中。
  4. 重启 Codex 让新的 skill 生效。

Codex — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Codex 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Codex 让新的 skill 生效。

Claude Code — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/antonbabenko/terraform-skill.git
  3. 将 "skills/terraform-skill" 文件夹复制到 Claude Code 的 skills 目录中。
  4. 重启 Claude Code 让新的 skill 生效。

Claude Code — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Claude Code 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Claude Code 让新的 skill 生效。

Cursor — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/antonbabenko/terraform-skill.git
  3. 将 "skills/terraform-skill" 文件夹复制到 Cursor 的 skills 目录中。
  4. 重启 Cursor 让新的 skill 生效。

Cursor — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Cursor 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Cursor 让新的 skill 生效。

GitHub Copilot — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/antonbabenko/terraform-skill.git
  3. 将 "skills/terraform-skill" 文件夹复制到 GitHub Copilot 的 skills 目录中。
  4. 重启 GitHub Copilot 让新的 skill 生效。

GitHub Copilot — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 GitHub Copilot 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 GitHub Copilot 让新的 skill 生效。

Windsurf — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/antonbabenko/terraform-skill.git
  3. 将 "skills/terraform-skill" 文件夹复制到 Windsurf 的 skills 目录中。
  4. 重启 Windsurf 让新的 skill 生效。

Windsurf — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Windsurf 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Windsurf 让新的 skill 生效。
查看 SKILL.md 原文
name: terraform-skill
description: 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.
license: Apache-2.0
metadata:
  author: Anton Babenko
  version: 1.17.1

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

发现问题?提交给管理员复核

评分:

评论 (0)

暂无评论,成为第一个评论者吧!