Terraform Skill for Claude
Comprehensive Terraform and OpenTofu guidance covering testing, modules, CI/CD, and production patterns. Based on terraform-best-practices.com and enterprise experience.
When to Use This Skill
Activate this skill when:
- - Creating new Terraform or OpenTofu configurations or modules
- Setting up testing infrastructure for IaC code
- Deciding between testing approaches (validate, plan, frameworks)
- Structuring multi-environment deployments
- Implementing CI/CD for infrastructure-as-code
- Reviewing or refactoring existing Terraform/OpenTofu projects
- Choosing between module patterns or state management approaches
Don't use this skill for:
- - Basic Terraform/OpenTofu syntax questions (Claude knows this)
- Provider-specific API reference (link to docs instead)
- Cloud platform questions unrelated to Terraform/OpenTofu
Core Principles
1. Code Structure Philosophy
Module Hierarchy:
| Type | When to Use | Scope |
|---|
| Resource Module | Single logical group of connected resources | VPC + subnets, Security group + rules |
| Infrastructure Module |
Collection of resource modules for a purpose | Multiple resource modules in one region/account |
|
Composition | Complete infrastructure | Spans multiple regions/accounts |
Hierarchy: Resource → Resource Module → Infrastructure Module → Composition
Directory Structure:
CODEBLOCK0
Key principle from terraform-best-practices.com:
- - Separate environments (prod, staging) from modules (reusable components)
- Use examples/ as both documentation and integration test fixtures
- Keep modules small and focused (single responsibility)
For detailed module architecture, see: Code Patterns: Module Types & Hierarchy
2. Naming Conventions
Resources:
CODEBLOCK1
Singleton Resources:
Use "this" when your module creates only one resource of that type:
✅ DO:
CODEBLOCK2
❌ DON'T use "this" for multiple resources:
CODEBLOCK3
Use descriptive names when creating multiple resources of the same type.
Variables:
CODEBLOCK4
Files:
- -
main.tf - Primary resources - INLINECODE2 - Input variables
- INLINECODE3 - Output values
- INLINECODE4 - Provider versions
- INLINECODE5 - Data sources (optional)
Testing Strategy Framework
Decision Matrix: Which Testing Approach?
| Your Situation | Recommended Approach | Tools | Cost |
|---|
| Quick syntax check | Static analysis | INLINECODE6 , INLINECODE7 | Free |
| Pre-commit validation |
Static + lint |
validate,
tflint,
trivy,
checkov | Free |
|
Terraform 1.6+, simple logic | Native test framework | Built-in
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 + mocking | Free |
|
Multi-cloud, complex | Full integration | Terratest + real infra | Med-High |
Testing Pyramid for Infrastructure
CODEBLOCK5
Native Test Best Practices (1.6+)
Before generating test code:
- 1. Validate schemas with Terraform MCP:
CODEBLOCK6
- 2. Choose correct command mode:
-
command = plan - Fast, for input validation
-
command = apply - Required for computed values and set-type blocks
- 3. Handle set-type blocks correctly:
- Cannot index with
[0]
- Use
for expressions to iterate
- Or use
command = apply to materialize
Common patterns:
- - S3 encryption rules: set (use for expressions)
- Lifecycle transitions: set (use for expressions)
- IAM policy statements: set (use for expressions)
For detailed testing guides, see:
Code Structure Standards
Resource Block Ordering
Strict ordering for consistency:
- 1.
count or for_each FIRST (blank line after) - Other arguments
- INLINECODE20 as last real argument
- INLINECODE21 after tags (if needed)
- INLINECODE22 at the very end (if needed)
CODEBLOCK7
Variable Block Ordering
- 1.
description (ALWAYS required) - INLINECODE24
- INLINECODE25
- INLINECODE26
- INLINECODE27 (when setting to false)
CODEBLOCK8
For complete structure guidelines, see: Code Patterns: Block Ordering & Structure
Count vs For_Each: When to Use Each
Quick Decision Guide
| Scenario | Use | Why |
|---|
| Boolean condition (create or don't) | INLINECODE28 | Simple on/off toggle |
| Simple numeric replication |
count = 3 | Fixed number of identical resources |
| Items may be reordered/removed |
for_each = toset(list) | Stable resource addresses |
| Reference by key |
for_each = map | Named access to resources |
| Multiple named resources |
for_each | Better maintainability |
Common Patterns
Boolean conditions:
CODEBLOCK9
Stable addressing with for_each:
CODEBLOCK10
For migration guides and detailed examples, see: Code Patterns: Count vs For_Each
Locals for Dependency Management
Use locals to ensure correct resource deletion order:
CODEBLOCK11
Why this matters:
- - Prevents deletion errors when destroying infrastructure
- Ensures correct dependency order without explicit INLINECODE33
- Particularly useful for VPC configurations with secondary CIDR blocks
For detailed examples, see: Code Patterns: Locals for Dependency Management
Module Development
Standard Module Structure
CODEBLOCK12
Best Practices Summary
Variables:
- - ✅ Always include INLINECODE34
- ✅ Use explicit
type constraints - ✅ Provide sensible
default values where appropriate - ✅ Add
validation blocks for complex constraints - ✅ Use
sensitive = true for secrets
Outputs:
- - ✅ Always include INLINECODE39
- ✅ Mark sensitive outputs with INLINECODE40
- ✅ Consider returning objects for related values
- ✅ Document what consumers should do with each output
For detailed module patterns, see:
CI/CD Integration
Recommended Workflow Stages
- 1. Validate - Format check + syntax validation + linting
- Test - Run automated tests (native or Terratest)
- Plan - Generate and review execution plan
- Apply - Execute changes (with approvals for production)
Cost Optimization Strategy
- 1. Use mocking for PR validation (free)
- Run integration tests only on main branch (controlled cost)
- Implement auto-cleanup (prevent orphaned resources)
- Tag all test resources (track spending)
For complete CI/CD templates, see:
Security & Compliance
Essential Security Checks
CODEBLOCK13
Common Issues to Avoid
❌ Don't:
- - Store secrets in variables
- Use default VPC
- Skip encryption
- Open security groups to 0.0.0.0/0
✅ Do:
- - Use AWS Secrets Manager / Parameter Store
- Create dedicated VPCs
- Enable encryption at rest
- Use least-privilege security groups
For detailed security guidance, see:
Version Management
Version Constraint Syntax
CODEBLOCK14
Strategy by Component
| Component | Strategy | Example |
|---|
| Terraform | Pin minor version | INLINECODE41 |
| Providers |
Pin major version |
version = "~> 5.0" |
|
Modules (prod) | Pin exact version |
version = "5.1.2" |
|
Modules (dev) | Allow patch updates |
version = "~> 5.1" |
Update Workflow
CODEBLOCK15
For detailed version management, see: Code Patterns: Version Management
Modern Terraform Features (1.0+)
Feature Availability by Version
| Feature | Version | Use Case |
|---|
| INLINECODE45 function | 0.13+ | Safe fallbacks, replaces INLINECODE46 |
| INLINECODE47 |
1.1+ | Prevent null values in variables |
|
moved blocks | 1.1+ | Refactor without destroy/recreate |
|
optional() with defaults | 1.3+ | Optional object attributes |
| Native testing | 1.6+ | Built-in test framework |
| Mock providers | 1.7+ | Cost-free unit testing |
| Provider functions | 1.8+ | Provider-specific data transformation |
| Cross-variable validation | 1.9+ | Validate relationships between variables |
| Write-only arguments | 1.11+ | Secrets never stored in state |
Quick Examples
CODEBLOCK16
For complete patterns and examples, see: Code Patterns: Modern Terraform Features
Version-Specific Guidance
Terraform 1.0-1.5
- - Use Terratest for testing
- No native testing framework available
- Focus on static analysis and plan validation
Terraform 1.6+ / OpenTofu 1.6+
- - New: Native
terraform test / tofu test command - Consider migrating from external frameworks for simple tests
- Keep Terratest only for complex integration tests
Terraform 1.7+ / OpenTofu 1.7+
- - New: Mock providers for unit testing
- Reduce cost by mocking external dependencies
- Use real integration tests for final validation
Terraform vs OpenTofu
Both are fully supported by this skill. For licensing, governance, and feature comparison, see Quick Reference: Terraform vs OpenTofu.
Detailed Guides
This skill uses progressive disclosure - essential information is in this main file, detailed guides are available when needed:
📚 Reference Files:
- - Testing Frameworks - In-depth guide to static analysis, native tests, and Terratest
- Module Patterns - Module structure, variable/output best practices, ✅ DO vs ❌ DON'T patterns
- CI/CD Workflows - GitHub Actions, GitLab CI templates, cost optimization, automated cleanup
- Security & Compliance - Trivy/Checkov integration, secrets management, compliance testing
- Quick Reference - Command cheat sheets, decision flowcharts, troubleshooting guide
How to use: When you need detailed information on a topic, reference the appropriate guide. Claude will load it on demand to provide comprehensive guidance.
License
This skill is licensed under the Apache License 2.0. See the LICENSE file for full terms.
Copyright © 2026 Anton Babenko
Terraform 技能 for Claude
涵盖测试、模块、CI/CD和生产模式的全面Terraform和OpenTofu指导。基于terraform-best-practices.com和企业实践经验。
何时使用此技能
在以下情况下激活此技能:
- - 创建新的Terraform或OpenTofu配置或模块
- 为IaC代码设置测试基础设施
- 在测试方法(validate、plan、框架)之间做决策
- 构建多环境部署结构
- 实施基础设施即代码的CI/CD
- 审查或重构现有的Terraform/OpenTofu项目
- 在模块模式或状态管理方法之间做选择
不要将此技能用于:
- - 基础的Terraform/OpenTofu语法问题(Claude已掌握)
- 特定提供商的API参考(请链接到文档)
- 与Terraform/OpenTofu无关的云平台问题
核心原则
1. 代码结构理念
模块层级:
| 类型 | 使用时机 | 范围 |
|---|
| 资源模块 | 单一逻辑组的关联资源 | VPC + 子网、安全组 + 规则 |
| 基础设施模块 |
为特定目的组合的资源模块集合 | 同一区域/账户中的多个资源模块 |
|
组合 | 完整的基础设施 | 跨多个区域/账户 |
层级结构: 资源 → 资源模块 → 基础设施模块 → 组合
目录结构:
environments/ # 环境特定配置
├── prod/
├── staging/
└── dev/
modules/ # 可复用模块
├── networking/
├── compute/
└── data/
examples/ # 模块使用示例(也可作为测试)
├── complete/
└── minimal/
来自terraform-best-practices.com的关键原则:
- - 将环境(prod、staging)与模块(可复用组件)分离
- 使用examples/作为文档和集成测试夹具
- 保持模块小而专注(单一职责)
有关详细模块架构,请参见: 代码模式:模块类型与层级
2. 命名约定
资源:
hcl
好:描述性、上下文相关
resource aws
instance webserver { }
resource aws
s3bucket application_logs { }
好:对于单例资源(该类型只有一个)使用this
resource aws_vpc this { }
resource aws
securitygroup this { }
避免:对非单例资源使用通用名称
resource aws_instance main { }
resource aws
s3bucket bucket { }
单例资源:
当你的模块只创建一个该类型的资源时,使用this:
✅ 正确做法:
hcl
resource aws_vpc this {} # 模块创建一个VPC
resource awssecuritygroup this {} # 模块创建一个安全组
❌ 不要对多个资源使用this:
hcl
resource aws_subnet this {} # 如果要创建多个子网
创建多个同类型资源时,使用描述性名称。
变量:
hcl
需要时添加上下文前缀
var.vpc
cidrblock # 不仅仅是cidr
var.database
instanceclass # 不仅仅是instance_class
文件:
- - main.tf - 主要资源
- variables.tf - 输入变量
- outputs.tf - 输出值
- versions.tf - 提供商版本
- data.tf - 数据源(可选)
测试策略框架
决策矩阵:选择哪种测试方法?
| 你的情况 | 推荐方法 | 工具 | 成本 |
|---|
| 快速语法检查 | 静态分析 | terraform validate、fmt | 免费 |
| 提交前验证 |
静态 + 代码检查 | validate、tflint、trivy、checkov | 免费 |
|
Terraform 1.6+,简单逻辑 | 原生测试框架 | 内置 terraform test | 免费-低 |
|
Pre-1.6,或具备Go专业知识 | 集成测试 | Terratest | 低-中 |
|
安全/合规重点 | 策略即代码 | OPA、Sentinel | 免费 |
|
成本敏感的工作流 | 模拟提供商(1.7+) | 原生测试 + 模拟 | 免费 |
|
多云、复杂场景 | 完整集成 | Terratest + 真实基础设施 | 中-高 |
基础设施测试金字塔
/\
/ \ 端到端测试(昂贵)
/\ - 完整环境部署
/ \ - 类生产环境设置
/\
/ \ 集成测试(中等)
/\ - 模块隔离测试
/ \ - 测试账户中的真实资源
/\ 静态分析(廉价)
- validate、fmt、lint
- 安全扫描
原生测试最佳实践(1.6+)
在生成测试代码之前:
- 1. 使用Terraform MCP验证模式:
搜索提供商文档 → 获取资源模式 → 识别块类型
- 2. 选择正确的命令模式:
- command = plan - 快速,用于输入验证
- command = apply - 需要计算值和集合类型块
- 3. 正确处理集合类型块:
- 不能使用[0]索引
- 使用for表达式进行迭代
- 或使用command = apply来物化
常见模式:
- - S3加密规则:集合(使用for表达式)
- 生命周期转换:集合(使用for表达式)
- IAM策略语句:集合(使用for表达式)
有关详细测试指南,请参见:
- - 测试框架指南 - 深入探讨静态分析、原生测试和Terratest
- 快速参考 - 决策流程图和命令速查表
代码结构标准
资源块排序
严格排序以确保一致性:
- 1. count或foreach放在最前面(后面空一行)
- 其他参数
- tags作为最后一个实际参数
- dependson在tags之后(如果需要)
- lifecycle放在最后(如果需要)
hcl
✅ 正确 - 正确的排序
resource aws
natgateway this {
count = var.create
natgateway ? 1 : 0
allocationid = awseip.this[0].id
subnetid = awssubnet.public[0].id
tags = {
Name = ${var.name}-nat
}
dependson = [awsinternet_gateway.this]
lifecycle {
createbeforedestroy = true
}
}
变量块排序
- 1. description(始终需要)
- type
- default
- validation
- nullable(当设置为false时)
hcl
variable environment {
description = 用于资源标记的环境名称
type = string
default = dev
validation {
condition = contains([dev, staging, prod], var.environment)
error_message = 环境必须是以下之一:dev、staging、prod。
}
nullable = false
}
有关完整结构指南,请参见: 代码模式:块排序与结构
Count vs For_Each:何时使用
快速决策指南
| 场景 | 使用 | 原因 |
|---|
| 布尔条件(创建或不创建) | count = condition ? 1 : 0 | 简单的开关切换 |
| 简单的数字复制 |
count = 3 | 固定数量的相同资源 |
| 项目可能被重新排序/移除 | for_each = toset(list) | 稳定的资源地址 |
| 按键引用 | for_each = map | 命名访问资源 |
| 多个命名资源 | for_each | 更好的可维护性 |
常见模式
布尔条件:
hcl
✅ 正确 - 布尔条件
resource aws
natgateway this {
count = var.create
natgateway ? 1 : 0
# ...
}
使用for_each的稳定寻址:
hcl
✅ 正确 - 移除