Terraform 用于以代码方式管理基础设施(Infrastructure as Code),通过 Terraform CLI 完成基础设施的初始化、变更预览、应用、销毁与状态管理。
用途 本条目围绕 Terraform CLI 的常用操作展开,帮助在代码层面声明和管理基础设施,覆盖从初始化、计划、应用到销毁的完整流程,以及状态、输出、校验、格式化、Provider、工作区和资源导入等辅助操作。
主要能力与使用方式 初始化:cd /workspace/infra && terraform init 计划(预览变更):cd /workspace/infra && terraform plan -no-color 针对特定目标计划:cd /workspace/infra && terraform plan -target=aws_instance.web -no-color 应用变更:cd /workspace/infra && terraform apply -auto-approve -no-color 销毁:cd /workspace/infra && terraform destroy -auto-approve -no-color 查看状态:cd /workspace/infra && terraform state list;cd /workspace/infra && terraform state show aws_instance.web 输出值:cd /workspace/infra && terraform output -json | jq . 校验配置:cd /workspace/infra && terraform validate -no-color 格式检查:cd /workspace/infra && terraform fmt -check -recursive -no-color 查看 Provider:cd /workspace/infra && terraform providers 工作区管理:terraform workspace list;terraform workspace select staging 导入已有资源:cd /workspace/infra && terraform import aws_instance.web i-1234567890abcdef0
适用场景 适用于在 /workspace/infra 目录下对基础设施进行声明式管理,包括初始化工作目录、预览并应用变更、查看与操作状态、读取输出、校验与格式化配置、查看 Provider、切换工作区以及将已有资源纳入管理。
限制与注意事项 始终在 apply 之前运行 terraform plan 以审查变更。 在非终端环境中使用 -no-color 标志以获得干净输出。 未经用户明确确认,绝不运行 terraform destroy。 使用工作区或独立状态文件实现环境隔离。 后端配置(S3、Azure Blob、GCS)应设置在 Terraform 配置中,而不是通过 CLI。