关于 terraform
面向 Terraform 基础设施配置的开发指南,涵盖项目结构、Provider、变量、资源、模块及工作流。适合编写和组织 Terraform 配置的开发者。
主要功能
- 01Terraform 项目文件结构
- 02Provider 版本与配置
- 03变量及输入校验
- 04资源、数据源与模块
- 05init、fmt、validate 工作流
- 06远程状态与环境组织建议
适用场景
- 01搭建 Terraform 项目目录
- 02配置 Provider、变量和基础设施资源
- 03将可复用配置拆分为模块
- 04初始化并格式化、验证配置
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ dralgorhythm/ claude-agentic-framework --skill terraform安装后在 Claude Code 中输入/terraform确认已加载。
详细介绍
Terraform 开发
项目结构
terraform/
├── main.tf # Main resources
├── variables.tf # Input variables
├── outputs.tf # Output values
├── providers.tf # Provider config
├── versions.tf # Version constraints
├── terraform.tfvars # Variable values
└── modules/
└── vpc/
├── main.tf
├── variables.tf
└── outputs.tf
提供商配置
# versions.tf
terraform {
required_version = ">= 1.5"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
backend "s3" {
bucket = "terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-locks"
encrypt = true
}
}
provider "aws" {
region = var.aws_region
default_tags {
tags = {
Environment = var.environment
ManagedBy = "terraform"
}
}
}
变量
# variables.tf
variable "environment" {
description = "Environment name"
type = string
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "Environment must be dev, staging, or prod."
}
}
variable "instance_config" {
description = "EC2 instance configuration"
type = object({
instance_type = string
ami_id = string
volume_size = number
})
default = {
instance_type = "t3.micro"
ami_id = "ami-12345678"
volume_size = 20
}
}
资源
# main.tf
resource "aws_vpc" "main" {
cidr_block = var.vpc_cidr
enable_dns_hostnames = true
tags = {
Name = "${var.project}-vpc"
}
}
resource "aws_subnet" "private" {
count = length(var.availability_zones)
vpc_id = aws_vpc.main.id
cidr_block = cidrsubnet(var.vpc_cidr, 8, count.index)
availability_zone = var.availability_zones[count.index]
tags = {
Name = "${var.project}-private-${count.index + 1}"
}
}
模块
# Using a module
module "vpc" {
source = "./modules/vpc"
project = var.project
environment = var.environment
cidr_block = "10.0.0.0/16"
}
# Module outputs
output "vpc_id" {
value = module.vpc.vpc_id
}
数据源
data "aws_ami" "amazon_linux" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["amzn2-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_instance" "web" {
ami = data.aws_ami.amazon_linux.id
instance_type = var.instance_type
}
工作流
# Initialize
terraform init
# Format
terraform fmt -recursive
# Validate
terraform validate
# Plan
terraform plan -out=tfplan
# Apply
terraform apply tfplan
# Destroy
terraform destroy
最佳实践
- 使用带锁定功能的远程状态
- 使用模块实现复用
- 使用变量配置所有可配置值
- 使用数据源获取现有资源
- 为所有资源添加标签
- 使用工作区或目录区分环境
评论
支持 Markdown