用途
Terraform 技能围绕“基础设施即代码”展开,用于通过声明式配置文件预置、修改和销毁基础设施。当用户要求“创建基础设施”“编写 Terraform”等任务时,可依据本技能完成从初始化、变更预览到应用的完整工作流。
核心工作流
初始化(下载 provider):
terraform init
预览变更:
terraform plan
terraform plan -out=tfplan # 保存计划
应用变更:
terraform apply
terraform apply tfplan # 应用已保存的计划
terraform apply -auto-approve # 跳过确认
销毁资源:
terraform destroy
terraform destroy -target=aws_instance.web
格式化代码:
terraform fmt
terraform fmt -recursive
校验配置:
terraform validate
查看当前状态:
terraform show
terraform state list
terraform state show aws_instance.web
主要能力
基本配置
包含 terraform 块(required_version、required_providers、backend)、provider 声明等。示例:
terraform {
required_version = ">= 1.5"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
}
}
provider "aws" {
region = var.region
}
变量
支持 string、map(string)、list(string) 等类型,可设置默认值与描述。传参方式:
terraform plan -var="region=us-west-2"
terraform plan -var-file="production.tfvars"
自动加载文件:terraform.tfvars、*.auto.tfvars。
输出
通过 output 块导出值,可标记 sensitive。查看方式:
terraform output
terraform output instance_ip
terraform output -json
资源
支持资源定义及 lifecycle 块(create_before_destroy、prevent_destroy、ignore_changes)。示例包括 aws_instance、aws_s3_bucket、aws_security_group 等。
数据源
可查询已有资源,如 data "aws_ami"、data "aws_vpc",并在资源中引用其属性。
模块
支持使用远程模块(含 source 与 version)和本地模块(相对路径),并可引用模块输出。
状态管理
terraform import aws_instance.web i-1234567890abcdef0
terraform state mv aws_instance.old aws_instance.new
terraform state rm aws_instance.web
terraform state pull > state.json
terraform state replace-provider hashicorp/aws registry.terraform.io/hashicorp/aws
工作区
terraform workspace list
terraform workspace new staging
terraform workspace select production
配置中可通过 terraform.workspace 按工作区差异化取值。
常见模式
- 条件资源:count = var.enable_bastion ? 1 : 0
- for_each:如 toset(var.user_names)
- 动态块:dynamic "ingress"
- 本地值:locals { common_tags = {...} }
使用方式
依据用户需求,按上述核心工作流与配置示例编写和维护 Terraform 代码,覆盖初始化、计划、应用、状态操作、模块与工作区等环节。
适用场景
需要以代码方式创建、变更或销毁云基础设施,并需要模块化、状态管理与多环境(工作区)管理的场景。
限制
本资料未提供超出上述内容的额外功能、收费、价格或平台信息,相关内容暂未提供。