terraform-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Terraform 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
    .tf
    or
    .tfvars
    files
  • 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:
  1. Project layout - Environments as thin roots that call reusable modules.
  2. Versions and providers - Pin Terraform and provider versions; commit the lock file.
  3. Remote state - Encrypted, locked, per-environment state.
  4. Variables and outputs - Typed, validated inputs and minimal outputs.
  5. Secrets - Keep values out of code, state exposure in mind.
  6. Resources -
    for_each
    over
    count
    ,
    lifecycle
    , and tagging.
  7. Modules - Small, single-purpose, versioned.
  8. Refactoring -
    moved
    and
    import
    blocks instead of destroy/recreate.
  9. Safe workflow and CI - Plan is saved, reviewed, then applied.
  10. Debugging and anti-patterns - Common errors and what to avoid.
Examples use AWS for concreteness. The structure applies to any provider.
此 skill 提供可直接复制粘贴的模式和安全命令工作流,并按任务进行组织:
  1. 项目布局 - 将环境作为轻量根模块,用其调用可复用模块。
  2. 版本和 provider - 固定 Terraform 和 provider 版本;提交 lock file。
  3. 远程 state - 对 state 进行加密、加锁并按环境隔离。
  4. 变量和 outputs - 类型明确、经过验证的输入和最小化的 outputs。
  5. Secrets - 避免值进入代码,并注意 state 暴露风险。
  6. 资源 - 优先使用
    for_each
    而非
    count
    ,并善用
    lifecycle
    和 tagging。
  7. 模块 - 小型、单一用途且带版本控制。
  8. 重构 - 使用
    moved
    和
    import
    blocks,而非 destroy/recreate。
  9. 安全工作流和 CI - 保存 plan,审核后再 apply。
  10. 调试和反模式 - 常见错误及应避免的做法。
示例为便于理解使用 AWS。该结构适用于任何 provider。

Examples

示例

TaskJump to
Layout for dev/staging/prodProject Layout
Remote state with lockingRemote State
Validated variablesVariables and Outputs
Avoid secrets in state and codeSecrets
Rename a resource without destroying itRefactoring Without Destroying
Plan/apply in CISafe Workflow and CI
Lock or drift errorsDebugging

任务跳转至
开发、预发布和生产环境的布局项目布局
带锁定的远程 state远程 State
经过验证的变量变量和 Outputs

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.tfvars
Rules 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 (
    terraform.tfvars
    ), not by copy-pasted resources.
  • 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
undefined

versions.tf

versions.tf

terraform { required_version = ">= 1.10.0, < 2.0.0"
required_providers { aws = { source = "hashicorp/aws" version = "~> 5.40" } } }

```hcl
terraform { required_version = ">= 1.10.0, < 2.0.0"
required_providers { aws = { source = "hashicorp/aws" version = "~> 5.40" } } }

```hcl

providers.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
undefined
Local state 不适合团队使用,而且很容易丢失。请使用支持加密和锁定的远程 backend。
hcl
undefined

backend.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
    -backend-config
    or a partial config file when you need per-environment values.
  • 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
    -lock=false
    to get past a lock error. See Debugging.
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 不能引用变量。需要按环境提供值时,请使用
    -backend-config
    或 partial config file。
  • 启用 bucket versioning,以便从错误的 state 写入操作中恢复。
  • 阻止对 state bucket 的公开访问,并限制可以读取它的人员。State 通常包含敏感值。
  • 绝不要使用
    -lock=false
    绕过 lock 错误。请参阅调试。

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
    description
    . Modules are read far more often than written.
  • Give a
    default
    only when one is safe in every environment. Required inputs force the caller to decide.
  • Mark outputs that carry credentials
    sensitive = true
    . Note this only hides them from CLI output; they are still stored in state.
为输入指定类型并添加验证,让错误在 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 都要设置
    description
    。Modules 的阅读频率远高于编写频率。
  • 只有在所有环境中都安全时才设置
    default
    。必填输入可以迫使调用方作出明确决定。
  • 对携带凭据的 outputs 设置
    sensitive = true
    。注意,这只会隐藏 CLI 输出中的值;它们仍会存储在 state 中。

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
    .tf
    and committed
    .tfvars
    files. Supply them at runtime with
    TF_VAR_*
    environment variables or your CI secret store.
  • 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
undefined
Terraform state 会以明文存储资源属性,包括传入的或由 provider 生成的 passwords 和 keys。
应该:
  • 不要在
    .tf
    和已提交的
    .tfvars
    文件中保留 Secrets。请在运行时通过
    TF_VAR_*
    环境变量或 CI secret store 提供它们。
  • 引用 secret manager 中已经存在的 Secrets,而不是在 Terraform 中创建其值。
  • 在 Terraform 和 provider 版本支持时,使用 ephemeral values 和 write-only attributes,使值不会进入 state。
  • 对静态存储的 state 进行加密,并限制其读取权限。
  • 使用短期凭据进行身份验证(来自 CI 的 OIDC、assumed roles),而不是长期 access keys。
hcl
undefined

Read 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_each
,而非
count

count
identifies resources by index. Removing an item from the middle of a list shifts every later item down one index, so Terraform plans to modify or replace the resources after it (and destroy the last one) instead of just removing the one you meant to.
hcl
undefined
count
通过索引标识资源。从列表中间移除某项时,后续所有项的索引都会向前移动一位。因此,Terraform 会计划修改或替换其后的资源,并销毁最后一个资源,而不是只移除目标资源。
hcl
undefined

Fragile: 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
  }
}
  • prevent_destroy
    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
    removed
    block (Terraform >= 1.7):
hcl
removed {
  from = aws_s3_bucket.data

  lifecycle {
    destroy = false
  }
}
  • ignore_changes
    hides drift. Use it narrowly and add a comment saying why.
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)使用
    prevent_destroy
    ,可将意外销毁转化为 plan 错误。
  • prevent_destroy
    只能保护仍存在于配置中的资源。如果删除 resource block,Terraform 将不再看到该设置,并会计划销毁真实资源。要停止管理某个资源但不销毁它,请使用
    removed
    block(Terraform >= 1.7):
hcl
removed {
  from = aws_s3_bucket.data

  lifecycle {
    destroy = false
  }
}
  • ignore_changes
    会隐藏 drift。请谨慎使用,并添加说明原因的注释。

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
0.0.0.0/0
ingress rules except for deliberately public endpoints, and keep IAM policies to the specific actions and resources needed.
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
}
除非是刻意公开的 endpoint,否则应避免使用
0.0.0.0/0
ingress rules,并将 IAM policies 限制为所需的特定 actions 和 resources。

Modules

模块

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
undefined

Resource 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 applying

STOP: 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 line
terraform 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 中异常的 count

CI pipeline shape

CI pipeline 结构

yaml
undefined
yaml
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

调试

SymptomLikely causeWhat to do
Error acquiring the state lock
Another run holds the lock, or a run crashedConfirm no run is active, then
terraform force-unlock <LOCK_ID>
. Do not disable locking.
Plan shows changes you did not makeDrift, a provider upgrade, or a changed default
terraform plan -refresh-only
to see drift. Check the lock file diff.
Provider produced inconsistent result
Provider bug or version mismatchPin and upgrade the provider; check its issue tracker.
Cycle
error
Two resources depend on each otherBreak the loop with an intermediate resource or remove the redundant reference.
Resource already existsIt was created outside TerraformAdd an
import
block, then plan.
for_each
value depends on unknown values
Keys come from an attribute known only after applyKey by a static value, or apply in two steps with
-target
as a one-time exception.
Destroy and recreate on renameMissing
moved
block
Add a
moved
block, re-plan.
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 secrets
TF_LOG
output can contain credentials. Do not paste it into issues or CI logs without scrubbing it.
症状可能原因处理方式
Error acquiring the state lock
另一次运行持有 lock,或某次运行意外终止确认没有运行正在进行,然后执行
terraform force-unlock <LOCK_ID>
。不要禁用 locking。
Plan 显示并非由你发起的变更Drift、provider upgrade 或 default 发生变化执行
terraform plan -refresh-only
查看 drift。检查 lock file diff。
Provider produced inconsistent result
Provider bug 或版本不匹配固定并升级 provider;查看其 issue tracker。
Cycle
错误
两个 resources 相互依赖引入中间 resource 打破循环,或移除冗余引用。
Resource already exists它是在 Terraform 之外创建的添加
import
block,然后执行 plan。
for_each
value 依赖 unknown values
Keys 来自 apply 后才能确定的 attribute使用静态 value 作为 key,或将
-target
作为一次性例外,分两步 apply。
重命名时出现 destroy 和 recreate缺少
moved
block
添加
moved
block,然后重新 plan。
实用命令:
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
TF_LOG
输出可能包含凭据。在未清理敏感信息的情况下,不要将其粘贴到 issues 或 CI 日志中。

Anti-Patterns

反模式

Anti-patternWhy it hurtsInstead
terraform apply
without a saved plan
Applies something other than what was reviewed
plan -out
, review,
apply tfplan
-auto-approve
on a human workflow
Removes the last safety checkReserve it for pipelines that apply a reviewed plan
Local state for shared infrastructureLost state, no lockingRemote backend with locking
One huge state for everythingSlow plans, large blast radiusSplit by environment and domain
Secrets in
.tf
or committed
.tfvars
Leaked credentialsRuntime variables or a secret manager
Unpinned providers or modulesSurprise changes between runsVersion constraints plus the lock file
count
over a list of named things
Index shift causes destroys
for_each
with stable keys
-target
as routine practice
Skips dependencies, leaves state inconsistentFix the root cause; use only as a one-time exception
Editing state by handCorrupts state
moved
,
import
, or
terraform state
with a backup
Disabling locking to bypass a stuck lockConcurrent writes corrupt stateVerify and
force-unlock
the specific lock
反模式危害替代方案
未保存 plan 就执行
terraform apply
应用的内容会不同于审核过的内容
plan -out
,审核后执行
apply tfplan
在人工工作流中使用
-auto-approve
移除最后一道安全检查仅将其用于 apply 已审核 plan 的 pipelines
共享基础设施使用 local stateState 丢失且没有 locking使用支持 locking 的远程 backend
所有资源共用一个巨型 statePlan 缓慢,影响范围巨大按环境和领域拆分
Secrets 出现在
.tf
或已提交的
.tfvars
中
凭据泄露使用运行时 variables 或 secret manager
未固定 providers 或 modules不同运行之间出现意外变更使用版本约束和 lock file
对命名对象列表使用
count
索引移动导致资源被销毁使用具有稳定 keys 的
for_each
将
-target
作为常规做法
跳过 dependencies,导致 state 不一致修复根本原因;仅将其作为一次性例外
手动编辑 state损坏 state使用
moved
、
import
,或在备份后使用
terraform state
禁用 locking 以绕过卡住的 lock并发写入会损坏 state验证并对特定 lock 执行
force-unlock

Checklist

检查清单

Before opening a PR:
  • terraform fmt -recursive
    and
    terraform validate
    pass
  • Terraform and provider versions are pinned;
    .terraform.lock.hcl
    is committed
  • State is remote, encrypted, and locked
  • No secrets in code,
    .tfvars
    , or outputs that are not
    sensitive
  • Variables have types, descriptions, and validation where a bad value is plausible
  • Stateful resources have
    prevent_destroy
    or an explicit reason they do not (and removals use a
    removed
    block with
    destroy = false
    )
  • A human approved the saved plan before it was applied
  • The plan was read: no unexpected destroys or replacements
  • Refactors use
    moved
    or
    import
    , not destroy and recreate
  • CI applies the saved, reviewed plan
提交 PR 前:
  • terraform fmt -recursive
    和
    terraform validate
    已通过
  • Terraform 和 provider 版本已固定,并已提交
    .terraform.lock.hcl
  • State 位于远程、已加密并启用 locking
  • 代码和
    .tfvars
    中没有 Secrets,未标记
    sensitive
    的 outputs 中也没有 Secrets
  • Variables 包含类型、描述,并在可能输入错误值时包含 validation
  • 有状态 resources 设置了
    prevent_destroy
    ,或明确说明了未设置的原因;移除 resources 时使用了带
    destroy = false
    的
    removed
    block
  • 人类已批准保存的 plan,然后才执行 apply
  • 已阅读 plan:不存在意外的 destroy 或 replacement
  • 重构使用
    moved
    或
    import
    ,而非 destroy 和 recreate
  • CI apply 的是已保存且经过审核的 plan

Related Skills

相关 Skills

  • kubernetes-patterns
    - cluster workloads once the infrastructure exists
  • docker-patterns
    - container images that Terraform-managed infrastructure runs
  • deployment-patterns
    - release and rollout strategies
  • security-review
    - broader security checklist
  • database-migrations
    - schema changes, distinct from infrastructure changes
  • kubernetes-patterns
    - 基础设施创建完成后运行 cluster workloads
  • docker-patterns
    - 为 Terraform 管理的基础设施构建 container images
  • deployment-patterns
    - release 和 rollout strategies
  • security-review
    - 更全面的 security checklist
  • database-migrations
    - schema changes,与基础设施变更不同