Terraform 工作流程与命令

掌握 Terraform 的标准工作流程和常用命令。

一、标准工作流程

编写配置 → 初始化 → 规划 → 应用 → 验证
   ↓         ↓       ↓      ↓       ↓
 .tf     terraform terraform terraform  查看
 文件      init     plan    apply    资源

1.1 工作流程详解

1. 编写配置(Write)

# main.tf
resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  
  tags = {
    Name = "WebServer"
  }
}

2. 初始化(Init)

terraform init
  • 下载 Provider 插件
  • 初始化后端配置
  • 下载模块依赖

3. 规划(Plan)

terraform plan
  • 对比当前状态和期望状态
  • 显示将要执行的变更
  • 不会实际修改资源

4. 应用(Apply)

terraform apply
  • 执行实际的资源创建/修改/删除
  • 更新状态文件
  • 需要确认(或使用 -auto-approve

5. 验证(Validate)

# 验证配置语法
terraform validate

# 格式化代码
terraform fmt

# 查看状态
terraform show

二、核心命令详解

2.1 terraform init

初始化 Terraform 工作目录。

# 基本初始化
terraform init

# 重新初始化(例如更换后端)
terraform init -reconfigure

# 仅升级 provider
terraform init -upgrade

# 从模块源更新
terraform init -upgrade -get=true

输出示例:

Initializing the backend...
Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 5.0"...
- Installing hashicorp/aws v5.31.0...

Terraform has been successfully initialized!

2.2 terraform plan

生成执行计划。

# 基本 plan
terraform plan

# 保存计划到文件
terraform plan -out=tfplan

# 针对特定资源
terraform plan -target=aws_instance.web

# 销毁计划
terraform plan -destroy

# 使用变量文件
terraform plan -var-file="prod.tfvars"

计划输出符号:

+ create      # 创建新资源
~ update      # 就地更新
-/+ replace   # 先删除后创建
- destroy     # 删除资源
<= read       # 读取数据源

示例输出:

Terraform will perform the following actions:

  # aws_instance.web will be created
  + resource "aws_instance" "web" {
      + ami           = "ami-0c55b159cbfafe1f0"
      + instance_type = "t2.micro"
      + id            = (known after apply)
      ...
    }

Plan: 1 to add, 0 to change, 0 to destroy.

2.3 terraform apply

应用更改。

# 交互式应用
terraform apply

# 自动批准
terraform apply -auto-approve

# 使用保存的计划
terraform apply tfplan

# 针对特定资源
terraform apply -target=aws_instance.web

# 并行度控制
terraform apply -parallelism=10

2.4 terraform destroy

销毁资源。

# 销毁所有资源
terraform destroy

# 自动批准
terraform destroy -auto-approve

# 销毁特定资源
terraform destroy -target=aws_instance.web

2.5 terraform validate

验证配置语法。

# 验证当前目录
terraform validate

# 详细输出
terraform validate -json

输出示例:

Success! The configuration is valid.

2.6 terraform fmt

格式化代码。

# 格式化当前目录
terraform fmt

# 递归格式化
terraform fmt -recursive

# 检查但不修改
terraform fmt -check

# 显示差异
terraform fmt -diff

2.7 terraform show

显示状态或计划。

# 显示当前状态
terraform show

# 显示保存的计划
terraform show tfplan

# JSON 格式输出
terraform show -json

2.8 terraform output

查看输出值。

# 显示所有输出
terraform output

# 显示特定输出
terraform output instance_ip

# JSON 格式
terraform output -json

# 原始值(无引号)
terraform output -raw instance_ip

三、状态管理命令

3.1 terraform state list

列出状态中的资源。

# 列出所有资源
terraform state list

# 过滤资源
terraform state list aws_instance.*

3.2 terraform state show

显示资源详情。

terraform state show aws_instance.web

输出示例:

# aws_instance.web:
resource "aws_instance" "web" {
    ami           = "ami-0c55b159cbfafe1f0"
    instance_type = "t2.micro"
    id            = "i-0123456789abcdef0"
    ...
}

3.3 terraform state mv

移动资源。

# 重命名资源
terraform state mv aws_instance.old aws_instance.new

# 移动到模块
terraform state mv aws_instance.web module.app.aws_instance.web

# 跨状态文件移动
terraform state mv -state-out=new.tfstate aws_instance.web aws_instance.web

3.4 terraform state rm

从状态中删除资源。

# 删除资源(不删除实际资源)
terraform state rm aws_instance.temp

# 删除模块
terraform state rm module.old_module

3.5 terraform state pull/push

# 拉取远程状态
terraform state pull > terraform.tfstate.backup

# 推送本地状态到远程
terraform state push terraform.tfstate

四、导入现有资源

4.1 terraform import

# 导入 EC2 实例
terraform import aws_instance.web i-1234567890abcdef0

# 导入 S3 桶
terraform import aws_s3_bucket.data my-bucket-name

步骤:

  1. 先写资源配置:
resource "aws_instance" "web" {
  # 暂时留空
}
  1. 导入资源:
terraform import aws_instance.web i-1234567890abcdef0
  1. 查看导入的资源:
terraform state show aws_instance.web
  1. 完善配置以匹配导入的资源。

五、工作区管理

5.1 terraform workspace

# 列出工作区
terraform workspace list

# 创建新工作区
terraform workspace new dev
terraform workspace new staging
terraform workspace new prod

# 切换工作区
terraform workspace select dev

# 查看当前工作区
terraform workspace show

# 删除工作区
terraform workspace delete dev

5.2 工作区用途

resource "aws_instance" "web" {
  ami           = "ami-xxx"
  instance_type = terraform.workspace == "prod" ? "t2.large" : "t2.micro"
  
  tags = {
    Name        = "web-${terraform.workspace}"
    Environment = terraform.workspace
  }
}

六、调试和日志

6.1 启用详细日志

# 设置日志级别
export TF_LOG=DEBUG
export TF_LOG=TRACE  # 最详细
export TF_LOG=INFO
export TF_LOG=WARN
export TF_LOG=ERROR

# 日志输出到文件
export TF_LOG_PATH=./terraform.log

# 运行命令
terraform apply

6.2 关闭日志

unset TF_LOG
unset TF_LOG_PATH

七、常用命令组合

7.1 完整部署流程

# 1. 初始化
terraform init

# 2. 验证配置
terraform validate

# 3. 格式化代码
terraform fmt -recursive

# 4. 生成计划
terraform plan -out=tfplan

# 5. 查看计划
terraform show tfplan

# 6. 应用变更
terraform apply tfplan

# 7. 查看输出
terraform output

7.2 环境切换流程

# 切换到生产环境
terraform workspace select prod
terraform plan -var-file="prod.tfvars"
terraform apply -var-file="prod.tfvars"

# 切换回开发环境
terraform workspace select dev

7.3 灾难恢复

# 1. 备份状态
terraform state pull > backup.tfstate

# 2. 查看所有资源
terraform state list

# 3. 如需恢复,推送备份
terraform state push backup.tfstate

八、命令速查表

命令 用途 常用参数
init 初始化项目 -upgrade, -reconfigure
plan 生成执行计划 -out, -target, -var-file
apply 应用变更 -auto-approve, -target
destroy 销毁资源 -auto-approve, -target
validate 验证配置 -json
fmt 格式化代码 -recursive, -check
show 显示状态/计划 -json
output 查看输出 -json, -raw
state list 列出资源 -
state show 显示资源详情 -
import 导入现有资源 -
workspace 管理工作区 new, select, list

九、最佳实践

9.1 Always Plan Before Apply

# ✅ 推荐
terraform plan -out=tfplan
terraform apply tfplan

# ❌ 避免(除非完全确定)
terraform apply -auto-approve

9.2 使用变量文件

# ✅ 推荐
terraform apply -var-file="prod.tfvars"

# ❌ 避免
terraform apply -var="var1=value1" -var="var2=value2" ...

9.3 保护生产环境

# 为生产环境创建脚本
# deploy-prod.sh
#!/bin/bash
set -e

echo "🚀 Deploying to PRODUCTION..."
terraform workspace select prod
terraform plan -var-file="prod.tfvars" -out=tfplan
echo "Review the plan above. Continue? (yes/no)"
read answer
if [ "$answer" = "yes" ]; then
    terraform apply tfplan
else
    echo "Deployment cancelled"
fi

小结

Terraform 的工作流程清晰且可预测:

  1. Init: 准备环境
  2. Plan: 预览变更
  3. Apply: 执行变更
  4. Manage: 管理状态

掌握这些命令和工作流程,你就可以高效地管理基础设施了。下一章我们将深入学习 HCL 语法的高级特性。