terraform-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Terraform Best Practices

Terraform最佳实践

Comprehensive optimization guide for Terraform and Infrastructure as Code, maintained by Terramate. Contains 37 rules across 10 categories, prioritized by impact to guide automated refactoring and code generation.
这是由Terramate维护的Terraform与基础设施即代码(IaC)综合优化指南,涵盖10个类别共37条规则,按影响优先级排序,可指导自动化重构与代码生成。

When to Apply

适用场景

Reference these guidelines when:
  • Writing new Terraform modules or configurations
  • Implementing infrastructure patterns (AWS, GCP, Azure, etc.)
  • Reviewing code for security and reliability issues
  • Refactoring existing Terraform/OpenTofu code
  • Optimizing state management and performance
  • Setting up team workflows and governance
在以下场景中可参考本指南:
  • 编写新的Terraform模块或配置
  • 实现基础设施架构(AWS、GCP、Azure等)
  • 评审代码中的安全与可靠性问题
  • 重构现有Terraform/OpenTofu代码
  • 优化状态管理与性能
  • 搭建团队工作流与治理规范

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Organization & WorkflowCRITICAL
org-
2State ManagementCRITICAL
state-
3Security Best PracticesCRITICAL
security-
4Module DesignHIGH
module-
5Resource OrganizationMEDIUM-HIGH
resource-
6Variable & Output PatternsMEDIUM
variable-
,
output-
7Language Best PracticesMEDIUM
language-
8Provider ConfigurationMEDIUM
provider-
9Performance OptimizationLOW-MEDIUM
perf-
10Testing & ValidationLOW
test-
优先级类别影响程度前缀
1组织与工作流关键
org-
2状态管理关键
state-
3安全最佳实践关键
security-
4模块设计
module-
5资源组织中高
resource-
6变量与输出模式
variable-
,
output-
7语言最佳实践
language-
8提供商配置
provider-
9性能优化中低
perf-
10测试与验证
test-

Quick Reference

快速参考

1. Organization & Workflow (CRITICAL) - 5 rules

1. 组织与工作流(关键)- 5条规则

  • org-version-control
    - All Terraform code in version control
  • org-workspaces
    - One workspace per environment per configuration
  • org-access-control
    - Control who can change what infrastructure
  • org-change-workflow
    - Formal process for infrastructure changes
  • org-audit-logging
    - Track all infrastructure changes
  • org-version-control
    - 所有Terraform代码纳入版本控制
  • org-workspaces
    - 每个配置的每个环境对应一个工作区
  • org-access-control
    - 控制基础设施变更权限
  • org-change-workflow
    - 建立基础设施变更的正式流程
  • org-audit-logging
    - 跟踪所有基础设施变更

2. State Management (CRITICAL) - 3 rules

2. 状态管理(关键)- 3条规则

  • state-remote-backend
    - Always use remote state backends
  • state-locking
    - Enable state locking to prevent corruption
  • state-import
    - Import existing infrastructure into Terraform
  • state-remote-backend
    - 始终使用远程状态后端
  • state-locking
    - 启用状态锁定以防止数据损坏
  • state-import
    - 将现有基础设施导入Terraform管理

3. Security Best Practices (CRITICAL) - 3 rules

3. 安全最佳实践(关键)- 3条规则

  • security-no-hardcoded-secrets
    - Never hardcode secrets in code
  • security-credentials
    - Use proper credential management (OIDC, Vault, IAM roles)
  • security-iam-least-privilege
    - Follow least privilege principle
  • security-no-hardcoded-secrets
    - 切勿在代码中硬编码密钥
  • security-credentials
    - 使用合规的凭证管理方式(OIDC、Vault、IAM角色)
  • security-iam-least-privilege
    - 遵循最小权限原则

4. Module Design (HIGH) - 5 rules

4. 模块设计(高)- 5条规则

  • module-single-responsibility
    - One module per logical component
  • module-naming
    - Use consistent naming conventions (terraform-<PROVIDER>-<NAME>)
  • module-versioning
    - Version all module references
  • module-composition
    - Compose modules like building blocks
  • module-registry
    - Use existing community/shared modules
  • module-single-responsibility
    - 每个模块对应一个逻辑组件
  • module-naming
    - 使用统一命名规范(terraform-<提供商>-<名称>)
  • module-versioning
    - 为所有模块引用添加版本控制
  • module-composition
    - 像搭建积木一样组合模块
  • module-registry
    - 使用现有社区/共享模块

5. Resource Organization (MEDIUM-HIGH) - 5 rules

5. 资源组织(中高)- 5条规则

  • resource-naming
    - Use consistent naming conventions
  • resource-tagging
    - Tag all resources for cost tracking
  • resource-lifecycle
    - Use lifecycle blocks (prevent_destroy, ignore_changes)
  • resource-count-vs-foreach
    - Prefer for_each over count
  • resource-immutable
    - Prefer immutable infrastructure patterns
  • resource-naming
    - 使用统一命名规范
  • resource-tagging
    - 为所有资源添加标签以追踪成本
  • resource-lifecycle
    - 使用生命周期块(prevent_destroy、ignore_changes)
  • resource-count-vs-foreach
    - 优先使用for_each而非count
  • resource-immutable
    - 优先采用不可变基础设施模式

6. Variable & Output Patterns (MEDIUM) - 6 rules

6. 变量与输出模式(中)- 6条规则

  • variable-types
    - Use specific types, positive naming, nullable
  • variable-validation
    - Add validation rules for early error detection
  • variable-sensitive
    - Mark secrets as sensitive, no defaults
  • variable-descriptions
    - Document all variables with descriptions
  • output-descriptions
    - Document all outputs with descriptions
  • output-no-secrets
    - Never output secrets directly
  • variable-types
    - 使用特定类型、正向命名、可空设置
  • variable-validation
    - 添加验证规则以提前发现错误
  • variable-sensitive
    - 将密钥标记为敏感字段,不设默认值
  • variable-descriptions
    - 为所有变量添加描述文档
  • output-descriptions
    - 为所有输出添加描述文档
  • output-no-secrets
    - 切勿直接输出密钥

7. Language Best Practices (MEDIUM) - 5 rules

7. 语言最佳实践(中)- 5条规则

  • language-no-heredoc-json
    - Use jsonencode/yamlencode, not HEREDOC
  • language-locals
    - Use locals to name complex expressions
  • language-linting
    - Run terraform fmt and tflint
  • language-data-sources
    - Use data sources instead of hardcoding
  • language-dynamic-blocks
    - Use dynamic blocks for DRY code
  • language-no-heredoc-json
    - 使用jsonencode/yamlencode,而非HEREDOC
  • language-locals
    - 使用locals命名复杂表达式
  • language-linting
    - 运行terraform fmt和tflint
  • language-data-sources
    - 使用数据源而非硬编码
  • language-dynamic-blocks
    - 使用动态块实现DRY代码

8. Provider Configuration (MEDIUM) - 1 rule

8. 提供商配置(中)- 1条规则

  • provider-version-constraints
    - Pin provider versions
  • provider-version-constraints
    - 固定提供商版本

9. Performance Optimization (LOW-MEDIUM) - 2 rules

9. 性能优化(中低)- 2条规则

  • perf-parallelism
    - Tune parallelism for large deployments
  • perf-debug
    - Enable debug logging for troubleshooting
  • perf-parallelism
    - 为大规模部署调整并行度
  • perf-debug
    - 启用调试日志以排查问题

10. Testing & Validation (LOW) - 2 rules

10. 测试与验证(低)- 2条规则

  • test-strategies
    - Testing pyramid (validate, lint, plan, integration)
  • test-policy-as-code
    - Implement policy checks (OPA, Checkov, tfsec)
  • test-strategies
    - 测试金字塔(验证、 lint、计划、集成)
  • test-policy-as-code
    - 实施策略检查(OPA、Checkov、tfsec)

How to Use

使用方法

Read individual rule files for detailed explanations and code examples:
rules/state-remote-backend.md
rules/security-no-hardcoded-secrets.md
rules/module-versioning.md
Each rule file contains:
  • Brief explanation of why it matters
  • Incorrect code example with explanation
  • Correct code example with explanation
  • Additional context and references
阅读单个规则文件获取详细说明与代码示例:
rules/state-remote-backend.md
rules/security-no-hardcoded-secrets.md
rules/module-versioning.md
每个规则文件包含:
  • 规则重要性的简要说明
  • 错误代码示例及解释
  • 正确代码示例及解释
  • 额外背景信息与参考资料

Full Compiled Document

完整编译文档

For the complete guide with all rules expanded:
AGENTS.md
如需查看包含所有扩展规则的完整指南,请查阅:
AGENTS.md