terraform-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTerraform Patterns
Terraform 模式
Production-grade Terraform (and OpenTofu) patterns for writing infrastructure code that is reviewable, repeatable, and safe to apply.
生产级 Terraform(和 OpenTofu)模式,用于编写可审查、可重复且可安全 apply 的基础设施代码。
When to Activate
启用场景
- Writing or reviewing or
.tffiles.tfvars - Structuring a repo into modules and environments
- Configuring a remote backend, state locking, or state migration
- Passing variables and handling secrets in infrastructure code
- Setting up plan/apply automation in CI
- Debugging a failed plan, state drift, a lock error, or a provider version conflict
- Refactoring resources without destroying them (,
moved)import
- 编写或审查 或
.tf文件.tfvars - 将仓库组织为模块和环境
- 配置远程 backend、state locking 或 state migration
- 在基础设施代码中传递变量和处理 Secrets
- 在 CI 中设置 plan/apply 自动化
- 调试失败的 plan、state drift、lock 错误或 provider 版本冲突
- 重构资源但不销毁它们(、
moved)import
When to Use
使用场景
Same as When to Activate above. This alias satisfies repo skill-format conventions. Use this skill any time you are writing, reviewing, or debugging Terraform or OpenTofu configuration.
与上面的 启用场景 相同。此别名符合仓库的 skill 格式约定。每当编写、审查或调试 Terraform 或 OpenTofu 配置时,都可以使用此 skill。
How It Works
工作方式
This skill gives copy-pasteable patterns and a safe command workflow, organized by task:
- Project layout - Environments as thin roots that call reusable modules.
- Versions and providers - Pin Terraform and provider versions; commit the lock file.
- Remote state - Encrypted, locked, per-environment state.
- Variables and outputs - Typed, validated inputs and minimal outputs.
- Secrets - Keep values out of code, state exposure in mind.
- Resources - over
for_each,count, and tagging.lifecycle - Modules - Small, single-purpose, versioned.
- Refactoring - and
movedblocks instead of destroy/recreate.import - Safe workflow and CI - Plan is saved, reviewed, then applied.
- Debugging and anti-patterns - Common errors and what to avoid.
Examples use AWS for concreteness. The structure applies to any provider.
此 skill 提供可直接复制粘贴的模式和安全命令工作流,并按任务进行组织:
- 项目布局 - 将环境作为轻量根模块,用其调用可复用模块。
- 版本和 provider - 固定 Terraform 和 provider 版本;提交 lock file。
- 远程 state - 对 state 进行加密、加锁并按环境隔离。
- 变量和 outputs - 类型明确、经过验证的输入和最小化的 outputs。
- Secrets - 避免值进入代码,并注意 state 暴露风险。
- 资源 - 优先使用 而非
for_each,并善用count和 tagging。lifecycle - 模块 - 小型、单一用途且带版本控制。
- 重构 - 使用 和
movedblocks,而非 destroy/recreate。import - 安全工作流和 CI - 保存 plan,审核后再 apply。
- 调试和反模式 - 常见错误及应避免的做法。
示例为便于理解使用 AWS。该结构适用于任何 provider。
Examples
示例
| Task | Jump to |
|---|---|
| Layout for dev/staging/prod | Project Layout |
| Remote state with locking | Remote State |
| Validated variables | Variables and Outputs |
| Avoid secrets in state and code | Secrets |
| Rename a resource without destroying it | Refactoring Without Destroying |
| Plan/apply in CI | Safe Workflow and CI |
| Lock or drift errors | Debugging |
Project Layout
项目布局
Keep environments as thin root modules. Put logic in reusable modules.
text
infra/
├── modules/
│ └── network/
│ ├── main.tf
│ ├── variables.tf
│ ├── outputs.tf
│ └── versions.tf
└── envs/
├── dev/
│ ├── main.tf
│ ├── backend.tf
│ ├── providers.tf
│ └── terraform.tfvars
└── prod/
├── main.tf
├── backend.tf
├── providers.tf
└── terraform.tfvarsRules of thumb:
- One state per environment and per blast-radius boundary (network, data, apps). A single giant state makes every plan slow and every mistake large.
- Environments differ by inputs (), not by copy-pasted resources.
terraform.tfvars - Do not use workspaces as a substitute for separate production and non-production state with separate credentials.
将环境保持为轻量根模块,把逻辑放入可复用模块。
text
infra/
├── modules/
│ └── network/
│ ├── main.tf
│ ├── variables.tf
│ ├── outputs.tf
│ └── versions.tf
└── envs/
├── dev/
│ ├── main.tf
│ ├── backend.tf
│ ├── providers.tf
│ └── terraform.tfvars
└── prod/
├── main.tf
├── backend.tf
├── providers.tf
└── terraform.tfvars经验法则:
- 每个环境以及每个影响范围边界(网络、数据、应用)使用独立的 state。单个巨型 state 会让每次 plan 都很慢,也会放大每个错误的影响。
- 环境应通过输入()区分,而不是复制粘贴资源。
terraform.tfvars - 不要使用 workspaces 替代具有独立凭据的生产与非生产 state。
Versions and Providers
版本和 Provider
Pin everything. Unpinned providers change behavior between runs.
hcl
undefined固定所有版本。未固定的 provider 会在不同运行之间改变行为。
hcl
undefinedversions.tf
versions.tf
terraform {
required_version = ">= 1.10.0, < 2.0.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.40"
}
}
}
```hclterraform {
required_version = ">= 1.10.0, < 2.0.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.40"
}
}
}
```hclproviders.tf
providers.tf
provider "aws" {
region = var.region
default_tags {
tags = {
Environment = var.environment
ManagedBy = "terraform"
Owner = var.owner
}
}
}
- Commit `.terraform.lock.hcl`. It records provider checksums so CI and teammates install identical providers.
- Do **not** commit the `.terraform/` directory or any `*.tfstate` file.
- Upgrade deliberately: `terraform init -upgrade`, review the lock file diff, then plan.provider "aws" {
region = var.region
default_tags {
tags = {
Environment = var.environment
ManagedBy = "terraform"
Owner = var.owner
}
}
}
- 提交 `.terraform.lock.hcl`。它会记录 provider checksums,确保 CI 和团队成员安装完全相同的 provider。
- **不要**提交 `.terraform/` 目录或任何 `*.tfstate` 文件。
- 有意识地执行升级:运行 `terraform init -upgrade`,审核 lock file 的 diff,然后再执行 plan。Remote State
远程 State
Local state does not work for teams and is easy to lose. Use a remote backend with encryption and locking.
hcl
undefinedLocal state 不适合团队使用,而且很容易丢失。请使用支持加密和锁定的远程 backend。
hcl
undefinedbackend.tf
backend.tf
terraform {
backend "s3" {
bucket = "example-org-tfstate-prod"
key = "network/terraform.tfstate"
region = "us-east-1"
encrypt = true
use_lockfile = true # S3-native locking (Terraform >= 1.10)
}
}
Older Terraform versions use a DynamoDB table for locking instead. Replace
`use_lockfile = true` with:
```hcl
dynamodb_table = "example-org-tfstate-lock"Backend rules:
- Backend blocks cannot reference variables. Pass values with or a partial config file when you need per-environment values.
-backend-config - Enable bucket versioning so a bad state write can be recovered.
- Block public access on the state bucket and restrict who can read it. State often contains sensitive values.
- Never use to get past a lock error. See Debugging.
-lock=false
terraform {
backend "s3" {
bucket = "example-org-tfstate-prod"
key = "network/terraform.tfstate"
region = "us-east-1"
encrypt = true
use_lockfile = true # S3-native locking (Terraform >= 1.10)
}
}
较旧的 Terraform 版本改用 DynamoDB table 进行锁定。请将
`use_lockfile = true` 替换为:
```hcl
dynamodb_table = "example-org-tfstate-lock"Backend 规则:
- Backend blocks 不能引用变量。需要按环境提供值时,请使用 或 partial config file。
-backend-config - 启用 bucket versioning,以便从错误的 state 写入操作中恢复。
- 阻止对 state bucket 的公开访问,并限制可以读取它的人员。State 通常包含敏感值。
- 绝不要使用 绕过 lock 错误。请参阅调试。
-lock=false
Variables and Outputs
变量和 Outputs
Type and validate inputs so mistakes fail at plan time.
hcl
variable "environment" {
type = string
description = "Deployment environment."
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "environment must be one of: dev, staging, prod."
}
}
variable "instance_count" {
type = number
description = "Number of application instances."
default = 2
validation {
condition = var.instance_count >= 1 && var.instance_count <= 20
error_message = "instance_count must be between 1 and 20."
}
}
variable "allowed_cidrs" {
type = list(string)
description = "CIDR blocks allowed to reach the service."
default = []
}hcl
output "vpc_id" {
description = "ID of the VPC."
value = aws_vpc.this.id
}
output "db_password" {
description = "Generated database password."
value = random_password.db.result
sensitive = true
}- Every variable and output gets a . Modules are read far more often than written.
description - Give a only when one is safe in every environment. Required inputs force the caller to decide.
default - Mark outputs that carry credentials . Note this only hides them from CLI output; they are still stored in state.
sensitive = true
为输入指定类型并添加验证,让错误在 plan 阶段就失败。
hcl
variable "environment" {
type = string
description = "Deployment environment."
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "environment must be one of: dev, staging, prod."
}
}
variable "instance_count" {
type = number
description = "Number of application instances."
default = 2
validation {
condition = var.instance_count >= 1 && var.instance_count <= 20
error_message = "instance_count must be between 1 and 20."
}
}
variable "allowed_cidrs" {
type = list(string)
description = "CIDR blocks allowed to reach the service."
default = []
}hcl
output "vpc_id" {
description = "ID of the VPC."
value = aws_vpc.this.id
}
output "db_password" {
description = "Generated database password."
value = random_password.db.result
sensitive = true
}- 每个 variable 和 output 都要设置 。Modules 的阅读频率远高于编写频率。
description - 只有在所有环境中都安全时才设置 。必填输入可以迫使调用方作出明确决定。
default - 对携带凭据的 outputs 设置 。注意,这只会隐藏 CLI 输出中的值;它们仍会存储在 state 中。
sensitive = true
Secrets
Secrets
Terraform state stores resource attributes in plain text, including passwords and keys that you pass in or that the provider generates.
Do:
- Keep secrets out of and committed
.tffiles. Supply them at runtime with.tfvarsenvironment variables or your CI secret store.TF_VAR_* - Reference secrets that already exist in a secret manager instead of creating the value in Terraform.
- Use ephemeral values and write-only attributes where your Terraform and provider versions support them, so the value never lands in state.
- Encrypt state at rest and restrict read access to it.
- Authenticate with short-lived credentials (OIDC from CI, assumed roles) rather than long-lived access keys.
hcl
undefinedTerraform state 会以明文存储资源属性,包括传入的或由 provider 生成的 passwords 和 keys。
应该:
- 不要在 和已提交的
.tf文件中保留 Secrets。请在运行时通过.tfvars环境变量或 CI secret store 提供它们。TF_VAR_* - 引用 secret manager 中已经存在的 Secrets,而不是在 Terraform 中创建其值。
- 在 Terraform 和 provider 版本支持时,使用 ephemeral values 和 write-only attributes,使值不会进入 state。
- 对静态存储的 state 进行加密,并限制其读取权限。
- 使用短期凭据进行身份验证(来自 CI 的 OIDC、assumed roles),而不是长期 access keys。
hcl
undefinedRead an existing secret instead of defining its value in code
Read an existing secret instead of defining its value in code
data "aws_secretsmanager_secret_version" "db" {
secret_id = "prod/app/db-password"
}
resource "aws_db_instance" "app" {
identifier = "app-${var.environment}"
...
password = data.aws_secretsmanager_secret_version.db.secret_string
}
> Reading a secret through a data source still places the value in state. Treat the state file as sensitive in every case.
Do not:
- Hardcode credentials in `provider` blocks.
- Commit `terraform.tfvars` files that contain secrets. Add them to `.gitignore`.
- Print secrets with `terraform output -json` in shared CI logs.data "aws_secretsmanager_secret_version" "db" {
secret_id = "prod/app/db-password"
}
resource "aws_db_instance" "app" {
identifier = "app-${var.environment}"
...
password = data.aws_secretsmanager_secret_version.db.secret_string
}
> 通过 data source 读取 Secret 仍会将该值放入 state。无论何种情况,都应将 state file 视为敏感文件。
不要:
- 在 `provider` blocks 中硬编码凭据。
- 提交包含 Secrets 的 `terraform.tfvars` 文件。请将它们添加到 `.gitignore`。
- 在共享的 CI 日志中使用 `terraform output -json` 打印 Secrets。Resources
资源
Prefer for_each
over count
for_eachcount优先使用 for_each
,而非 count
for_eachcountcounthcl
undefinedcounthcl
undefinedFragile: removing "b" shifts "c" into b's slot and destroys the last index
Fragile: removing "b" shifts "c" into b's slot and destroys the last index
resource "aws_iam_user" "bad" {
count = length(var.users)
name = var.users[count.index]
}
resource "aws_iam_user" "bad" {
count = length(var.users)
name = var.users[count.index]
}
Stable: each resource is keyed by its name; removing "b" destroys only "b"
Stable: each resource is keyed by its name; removing "b" destroys only "b"
resource "aws_iam_user" "good" {
for_each = toset(var.users)
name = each.key
}
Use `count` only for a simple on/off toggle:
```hcl
resource "aws_cloudwatch_log_group" "app" {
count = var.enable_logging ? 1 : 0
name = "/app/${var.environment}"
}resource "aws_iam_user" "good" {
for_each = toset(var.users)
name = each.key
}
仅在简单的开关场景中使用 `count`:
```hcl
resource "aws_cloudwatch_log_group" "app" {
count = var.enable_logging ? 1 : 0
name = "/app/${var.environment}"
}Lifecycle guards
生命周期保护
hcl
resource "aws_s3_bucket" "data" {
bucket = "example-org-data-${var.environment}"
lifecycle {
prevent_destroy = true
}
}
resource "aws_launch_template" "app" {
# ...
lifecycle {
create_before_destroy = true
}
}- on stateful resources (databases, buckets, encryption keys) turns an accidental destroy into a plan error.
prevent_destroy - only protects a resource that is still in the configuration. If you delete the resource block, Terraform no longer sees the setting and will plan to destroy the real resource. To stop managing a resource without destroying it, use a
prevent_destroyblock (Terraform >= 1.7):removed
hcl
removed {
from = aws_s3_bucket.data
lifecycle {
destroy = false
}
}- hides drift. Use it narrowly and add a comment saying why.
ignore_changes
hcl
resource "aws_s3_bucket" "data" {
bucket = "example-org-data-${var.environment}"
lifecycle {
prevent_destroy = true
}
}
resource "aws_launch_template" "app" {
# ...
lifecycle {
create_before_destroy = true
}
}- 对有状态资源(数据库、buckets、encryption keys)使用 ,可将意外销毁转化为 plan 错误。
prevent_destroy - 只能保护仍存在于配置中的资源。如果删除 resource block,Terraform 将不再看到该设置,并会计划销毁真实资源。要停止管理某个资源但不销毁它,请使用
prevent_destroyblock(Terraform >= 1.7):removed
hcl
removed {
from = aws_s3_bucket.data
lifecycle {
destroy = false
}
}- 会隐藏 drift。请谨慎使用,并添加说明原因的注释。
ignore_changes
Secure defaults
安全默认值
hcl
resource "aws_s3_bucket_public_access_block" "data" {
bucket = aws_s3_bucket.data.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}Avoid ingress rules except for deliberately public endpoints, and keep IAM policies to the specific actions and resources needed.
0.0.0.0/0hcl
resource "aws_s3_bucket_public_access_block" "data" {
bucket = aws_s3_bucket.data.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}除非是刻意公开的 endpoint,否则应避免使用 ingress rules,并将 IAM policies 限制为所需的特定 actions 和 resources。
0.0.0.0/0Modules
模块
A good module does one thing, exposes a small interface, and is versioned.
hcl
module "network" {
source = "../../modules/network"
environment = var.environment
cidr_block = "10.20.0.0/16"
}优秀的 module 只做一件事,暴露小而清晰的 interface,并进行版本管理。
hcl
module "network" {
source = "../../modules/network"
environment = var.environment
cidr_block = "10.20.0.0/16"
}Registry or git modules: pin a version or ref
Registry or git modules: pin a version or ref
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 5.0"
}
- Pin registry modules with `version` and git modules with `?ref=<tag>`. Never track a moving branch.
- Do not configure `provider` blocks inside child modules. Declare `required_providers` and let the root pass providers in.
- Prefer composition: a module takes IDs as inputs rather than creating everything itself.
- Do not wrap a single resource in a module that only forwards its arguments.module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 5.0"
}
- 使用 `version` 固定 registry modules,使用 `?ref=<tag>` 固定 git modules。绝不要跟踪不断变化的 branch。
- 不要在 child modules 中配置 `provider` blocks。应声明 `required_providers`,并由 root 传入 providers。
- 优先使用 composition:module 接收 IDs 作为输入,而不是自行创建所有资源。
- 不要用一个仅转发参数的 module 包装单个资源。Refactoring Without Destroying
无损重构
Renaming a resource or moving it into a module looks like a destroy plus a create. Tell Terraform it is the same object.
hcl
undefined重命名资源或将其移入 module,看起来就像是 destroy 加 create。应明确告诉 Terraform 这是同一个对象。
hcl
undefinedResource renamed in code: keep the existing object
Resource renamed in code: keep the existing object
moved {
from = aws_instance.web
to = aws_instance.app
}
moved {
from = aws_instance.web
to = aws_instance.app
}
Adopt an existing resource into state (Terraform >= 1.5)
Adopt an existing resource into state (Terraform >= 1.5)
import {
to = aws_s3_bucket.legacy
id = "example-org-legacy-bucket"
}
Always read the plan after a refactor. A correct `moved` block shows as "has moved" with no destroy.
Use `terraform state` commands only as a last resort, take a backup first, and never edit the state file by hand.import {
to = aws_s3_bucket.legacy
id = "example-org-legacy-bucket"
}
重构后务必阅读 plan。正确的 `moved` block 会显示为“has moved”,并且没有 destroy 操作。
仅将 `terraform state` commands 作为最后手段。使用前先备份,并且绝不要手动编辑 state file。Safe Workflow and CI
安全工作流和 CI
Format and validate locally, then plan, review, and apply the same plan.
bash
terraform fmt -recursive
terraform init
terraform validate
terraform plan -out=tfplan
terraform show tfplan # review before applying先在本地格式化并验证,然后执行 plan、审核并 apply 同一个 plan。
bash
terraform fmt -recursive
terraform init
terraform validate
terraform plan -out=tfplan
terraform show tfplan # review before applyingSTOP: get explicit human approval of the reviewed plan before the next command
STOP: get explicit human approval of the reviewed plan before the next command
terraform apply tfplan # applies exactly what was reviewed
An AI agent must not run `terraform apply` or `terraform destroy` on its own. Show the plan summary, wait for the user to approve it, and only then apply the saved plan.
Why `-out`: a bare `terraform apply` re-plans, so what runs can differ from what you reviewed.
Read the plan for:
- `-/+` (replace) and `-` (destroy) lines on stateful resources
- Changes you did not make, which indicate drift or a provider upgrade
- Unexpected counts in the summary lineterraform apply tfplan # applies exactly what was reviewed
AI Agent 不得自行运行 `terraform apply` 或 `terraform destroy`。应展示 plan summary,等待用户批准,然后才能 apply 已保存的 plan。
使用 `-out` 的原因:直接执行 `terraform apply` 会重新 plan,因此实际运行的内容可能与审核过的内容不同。
阅读 plan 时,应关注:
- 有状态资源上的 `-/+`(replace)和 `-`(destroy)行
- 非由你发起的变更,它们可能表示 drift 或 provider upgrade
- summary line 中异常的 countCI pipeline shape
CI pipeline 结构
yaml
undefinedyaml
undefined.github/workflows/terraform.yml (shape only)
.github/workflows/terraform.yml (shape only)
name: terraform
on:
pull_request:
paths: ["infra/**"]
permissions:
id-token: write # OIDC to the cloud provider, no stored keys
contents: read
pull-requests: write
jobs:
plan:
runs-on: ubuntu-latest
steps:
# Pin third-party actions to full commit SHAs, not movable tags
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: hashicorp/setup-terraform@dfe3c3f87815947d99a8997f908cb6525fc44e9e # v4.0.1
with:
terraform_version: 1.10.5 # must satisfy required_version and use_lockfile (>= 1.10)
- run: terraform fmt -check -recursive
working-directory: infra/envs/dev
- run: terraform init -input=false
working-directory: infra/envs/dev
- run: terraform validate
working-directory: infra/envs/dev
- run: terraform plan -input=false -out=tfplan
working-directory: infra/envs/dev
- Run `plan` on pull requests and post it for review. Run `apply` only from the main branch, after approval, using the saved plan.
- Use `-input=false` in automation so a missing variable fails instead of hanging.
- Give the plan job read-only credentials where the provider allows it, and keep the apply role separate.
- Consider a policy or static-analysis step (for example `tflint`, `checkov`, or `trivy config`) before apply.name: terraform
on:
pull_request:
paths: ["infra/**"]
permissions:
id-token: write # OIDC to the cloud provider, no stored keys
contents: read
pull-requests: write
jobs:
plan:
runs-on: ubuntu-latest
steps:
# Pin third-party actions to full commit SHAs, not movable tags
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: hashicorp/setup-terraform@dfe3c3f87815947d99a8997f908cb6525fc44e9e # v4.0.1
with:
terraform_version: 1.10.5 # must satisfy required_version and use_lockfile (>= 1.10)
- run: terraform fmt -check -recursive
working-directory: infra/envs/dev
- run: terraform init -input=false
working-directory: infra/envs/dev
- run: terraform validate
working-directory: infra/envs/dev
- run: terraform plan -input=false -out=tfplan
working-directory: infra/envs/dev
- 在 pull requests 上运行 `plan` 并发布结果供审核。仅从 main branch 在批准后使用已保存的 plan 执行 `apply`。
- 在自动化中使用 `-input=false`,这样缺少变量时会直接失败,而不是一直等待。
- 如果 provider 支持,应为 plan job 配置 read-only credentials,并将 apply role 分离开来。
- 考虑在 apply 前增加 policy 或 static-analysis 步骤,例如 `tflint`、`checkov` 或 `trivy config`。Debugging
调试
| Symptom | Likely cause | What to do |
|---|---|---|
| Another run holds the lock, or a run crashed | Confirm no run is active, then |
| Plan shows changes you did not make | Drift, a provider upgrade, or a changed default | |
| Provider bug or version mismatch | Pin and upgrade the provider; check its issue tracker. |
| Two resources depend on each other | Break the loop with an intermediate resource or remove the redundant reference. |
| Resource already exists | It was created outside Terraform | Add an |
| Keys come from an attribute known only after apply | Key by a static value, or apply in two steps with |
| Destroy and recreate on rename | Missing | Add a |
Useful commands:
bash
terraform state list # what is tracked
terraform state show aws_instance.app # inspect one resource
terraform plan -refresh-only # detect drift without proposing changes
terraform providers # which providers and versions are in use
TF_LOG=DEBUG terraform plan 2> debug.log # verbose logs; may contain secretsoutput can contain credentials. Do not paste it into issues or CI logs without scrubbing it.TF_LOG
| 症状 | 可能原因 | 处理方式 |
|---|---|---|
| 另一次运行持有 lock,或某次运行意外终止 | 确认没有运行正在进行,然后执行 |
| Plan 显示并非由你发起的变更 | Drift、provider upgrade 或 default 发生变化 | 执行 |
| Provider bug 或版本不匹配 | 固定并升级 provider;查看其 issue tracker。 |
| 两个 resources 相互依赖 | 引入中间 resource 打破循环,或移除冗余引用。 |
| Resource already exists | 它是在 Terraform 之外创建的 | 添加 |
| Keys 来自 apply 后才能确定的 attribute | 使用静态 value 作为 key,或将 |
| 重命名时出现 destroy 和 recreate | 缺少 | 添加 |
实用命令:
bash
terraform state list # what is tracked
terraform state show aws_instance.app # inspect one resource
terraform plan -refresh-only # detect drift without proposing changes
terraform providers # which providers and versions are in use
TF_LOG=DEBUG terraform plan 2> debug.log # verbose logs; may contain secrets输出可能包含凭据。在未清理敏感信息的情况下,不要将其粘贴到 issues 或 CI 日志中。TF_LOG
Anti-Patterns
反模式
| Anti-pattern | Why it hurts | Instead |
|---|---|---|
| Applies something other than what was reviewed | |
| Removes the last safety check | Reserve it for pipelines that apply a reviewed plan |
| Local state for shared infrastructure | Lost state, no locking | Remote backend with locking |
| One huge state for everything | Slow plans, large blast radius | Split by environment and domain |
Secrets in | Leaked credentials | Runtime variables or a secret manager |
| Unpinned providers or modules | Surprise changes between runs | Version constraints plus the lock file |
| Index shift causes destroys | |
| Skips dependencies, leaves state inconsistent | Fix the root cause; use only as a one-time exception |
| Editing state by hand | Corrupts state | |
| Disabling locking to bypass a stuck lock | Concurrent writes corrupt state | Verify and |
| 反模式 | 危害 | 替代方案 |
|---|---|---|
未保存 plan 就执行 | 应用的内容会不同于审核过的内容 | |
在人工工作流中使用 | 移除最后一道安全检查 | 仅将其用于 apply 已审核 plan 的 pipelines |
| 共享基础设施使用 local state | State 丢失且没有 locking | 使用支持 locking 的远程 backend |
| 所有资源共用一个巨型 state | Plan 缓慢,影响范围巨大 | 按环境和领域拆分 |
Secrets 出现在 | 凭据泄露 | 使用运行时 variables 或 secret manager |
| 未固定 providers 或 modules | 不同运行之间出现意外变更 | 使用版本约束和 lock file |
对命名对象列表使用 | 索引移动导致资源被销毁 | 使用具有稳定 keys 的 |
将 | 跳过 dependencies,导致 state 不一致 | 修复根本原因;仅将其作为一次性例外 |
| 手动编辑 state | 损坏 state | 使用 |
| 禁用 locking 以绕过卡住的 lock | 并发写入会损坏 state | 验证并对特定 lock 执行 |
Checklist
检查清单
Before opening a PR:
- and
terraform fmt -recursivepassterraform validate - Terraform and provider versions are pinned; is committed
.terraform.lock.hcl - State is remote, encrypted, and locked
- No secrets in code, , or outputs that are not
.tfvarssensitive - Variables have types, descriptions, and validation where a bad value is plausible
- Stateful resources have or an explicit reason they do not (and removals use a
prevent_destroyblock withremoved)destroy = false - A human approved the saved plan before it was applied
- The plan was read: no unexpected destroys or replacements
- Refactors use or
moved, not destroy and recreateimport - CI applies the saved, reviewed plan
提交 PR 前:
- 和
terraform fmt -recursive已通过terraform validate - Terraform 和 provider 版本已固定,并已提交
.terraform.lock.hcl - State 位于远程、已加密并启用 locking
- 代码和 中没有 Secrets,未标记
.tfvars的 outputs 中也没有 Secretssensitive - Variables 包含类型、描述,并在可能输入错误值时包含 validation
- 有状态 resources 设置了 ,或明确说明了未设置的原因;移除 resources 时使用了带
prevent_destroy的destroy = falseblockremoved - 人类已批准保存的 plan,然后才执行 apply
- 已阅读 plan:不存在意外的 destroy 或 replacement
- 重构使用 或
moved,而非 destroy 和 recreateimport - CI apply 的是已保存且经过审核的 plan
Related Skills
相关 Skills
- - cluster workloads once the infrastructure exists
kubernetes-patterns - - container images that Terraform-managed infrastructure runs
docker-patterns - - release and rollout strategies
deployment-patterns - - broader security checklist
security-review - - schema changes, distinct from infrastructure changes
database-migrations
- - 基础设施创建完成后运行 cluster workloads
kubernetes-patterns - - 为 Terraform 管理的基础设施构建 container images
docker-patterns - - release 和 rollout strategies
deployment-patterns - - 更全面的 security checklist
security-review - - schema changes,与基础设施变更不同
database-migrations