mcpField
T
terraform

terraform

github.com/i9wa4云与 DevOps1246 次安装今天更新
代码仓库

关于 terraform

面向 Terraform 使用者的开发参考技能,涵盖 CLI、资源与模块、状态管理、变量和安全实践。还介绍 HCP Terraform 的协作、策略和远程状态功能。

主要功能

  1. 01Terraform 初始化、规划与应用命令
  2. 02资源生命周期与元参数
  3. 03模块设计与来源配置
  4. 04状态、远程后端与锁定
  5. 05变量、输出及敏感数据处理
  6. 06HCP Terraform 工作区与协作

适用场景

  1. 01检查变更计划后再应用基础设施修改
  2. 02管理远程状态并避免并发修改
  3. 03构建可复用的 Terraform 模块
  4. 04处理变量、凭据与状态文件安全

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/i9wa4/dotfiles --skill terraform

安装后在 Claude Code 中输入/terraform确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

examples/module-skeleton/
README.md
main.tf
versions.tf

详细介绍

Terraform 专家工程师技能

本技能提供 Terraform 开发的全面指南。

1. Terraform CLI 基本命令

1.1. 初始化和规划
# Initialize workspace (download providers)
terraform init

# Initialize with backend config
terraform init -backend-config="bucket=my-terraform-state"

# Check execution plan
terraform plan

# Save execution plan to file
terraform plan -out=tfplan

# Plan specific resource only
terraform plan -target=aws_instance.example
1.2. 应用和销毁

警告:这些命令会修改基础设施。 请务必先运行 terraform plan,并征求用户许可。

# Apply changes
terraform apply

# Apply saved plan
terraform apply tfplan

# Auto-approve apply (for CI/CD)
terraform apply -auto-approve

# Destroy resources
terraform destroy

# Destroy specific resource only
terraform destroy -target=aws_instance.example
1.3. 状态管理
# Check state
terraform state list

# Show resource details
terraform state show aws_instance.example

# Move resource (for refactoring)
terraform state mv aws_instance.old aws_instance.new

# Import existing resource
terraform import aws_instance.example i-1234567890abcdef0

# Remove resource from state (keeps actual resource)
terraform state rm aws_instance.example
1.4. 其他实用命令
# Validate configuration
terraform validate

# Format
terraform fmt

# Format recursively
terraform fmt -recursive

# Check outputs
terraform output

# Output in JSON format
terraform output -json

# Interactive console (for testing expressions)
terraform console

# Lock providers
terraform providers lock -platform=linux_amd64 -platform=darwin_amd64

2. 资源管理

2.1. 基本资源块结构
resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  tags = {
    Name = "example-instance"
  }
}
2.2. 元参数
  • depends_on:显式依赖关系
  • count:资源复制(基于索引)
  • for_each:资源复制(基于键)
  • provider:指定备用提供程序
  • lifecycle:生命周期控制
2.3. 生命周期设置
resource "aws_instance" "example" {
  # ...

  lifecycle {
    create_before_destroy = true  # Create new first on replacement
    prevent_destroy       = true  # Prevent deletion
    ignore_changes        = [tags] # Attributes to ignore changes
    replace_triggered_by  = [null_resource.trigger.id]
  }
}

3. 模块设计

3.1. 调用模块
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.0.0"

  name = "my-vpc"
  cidr = "10.0.0.0/16"
}
3.2. 模块源类型
  • 本地路径:./modules/vpc
  • Terraform Registry:hashicorp/consul/aws
  • GitHub:github.com/hashicorp/example
  • S3:s3::https://s3-eu-west-1.amazonaws.com/bucket/module.zip
3.3. 模块最佳实践
  • 标准文件结构:main.tf、variables.tf、outputs.tf
  • 使用 README.md 编写文档
  • 设置有意义的默认值
  • 使用 validation 块验证输入

4. 状态管理

4.1. 远程后端配置
terraform {
  backend "s3" {
    bucket         = "my-terraform-state"
    key            = "prod/terraform.tfstate"
    region         = "ap-northeast-1"
    encrypt        = true
    dynamodb_table = "terraform-locks"
  }
}
4.2. 状态管理最佳实践
  • 使用远程后端(团队开发的必备条件)
  • 启用状态锁定(防止并发执行)
  • 启用加密
  • 不要直接编辑状态文件(使用 terraform state 命令)
  • 为每个环境分开使用状态文件

5. 变量和输出

5.1. 输入变量
variable "instance_type" {
  type        = string
  description = "EC2 instance type"
  default     = "t2.micro"

  validation {
    condition     = contains(["t2.micro", "t2.small", "t2.medium"], var.instance_type)
    error_message = "Please specify an allowed instance type"
  }
}
5.2. 变量设置方式(优先级顺序)
  1. 命令行 -var、-var-file
  2. *.auto.tfvars 文件
  3. terraform.tfvars.json
  4. terraform.tfvars
  5. 环境变量 TF_VAR_*
  6. 默认值
5.3. 敏感数据处理
variable "db_password" {
  type      = string
  sensitive = true  # Mask in output
}

output "connection_string" {
  value     = "postgres://user:${var.db_password}@host/db"
  sensitive = true  # Output contains sensitive data
}

注意:敏感数据会以明文形式存储在状态文件中。 建议使用远程后端加密或 HCP Terraform。

6. 提供程序

6.1. 提供程序声明
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "ap-northeast-1"
}
6.2. 多个提供程序
provider "aws" {
  alias  = "us_east"
  region = "us-east-1"
}

provider "aws" {
  alias  = "ap_northeast"
  region = "ap-northeast-1"
}

resource "aws_instance" "us" {
  provider = aws.us_east
  # ...
}

7. 内置函数

7.1. 常用函数
# String operations
join("-", ["foo", "bar"])          # "foo-bar"
split(",", "a,b,c")                # ["a", "b", "c"]
format("Hello, %s!", "World")      # "Hello, World!"

# Collection operations
length(["a", "b", "c"])            # 3
lookup(map, key, default)          # Get value from map
merge(map1, map2)                  # Merge maps
flatten([["a"], ["b", "c"]])       # ["a", "b", "c"]

# Type conversions
tostring(123)                      # "123"
tolist(set)                        # Set to list
tomap(object)                      # Object to map

# Conditional expressions
coalesce("", "default")            # "default" (first non-empty value)
try(expression, fallback)          # Fallback on error

8. HCP Terraform / Terraform Cloud

8.1. 主要功能
  • 远程状态管理(加密、版本控制)
  • 团队协作
  • 策略执行(Sentinel)
  • 私有模块注册表
  • VCS 集成(GitHub、GitLab 等)
  • 成本估算
8.2. 工作区配置
terraform {
  cloud {
    organization = "my-org"

    workspaces {
      name = "my-workspace"
    }
  }
}

9. 安全最佳实践

9.1. 凭据管理
  • 不要硬编码
  • 使用环境变量或身份验证文件
  • 建议使用 IAM 角色 / 服务账号
  • 集成 HashiCorp Vault
9.2. 状态文件安全
  • 使用加密后端
  • 设置适当的访问控制
  • 将 .terraform/ 添加到 .gitignore
  • 将 *.tfvars 添加到 .gitignore(如果包含敏感信息)

10. 参考链接

评论

支持 Markdown