Terraform 基础设施即代码:从零开始管理云资源
Mei Lin | 2026-08-27T20:55:41 | DevOps, Cloud
使用 Terraform 管理 AWS 云资源,涵盖 Provider 配置、资源定义、变量和模块化设计等基础概念。
# Terraform 基础设施即代码入门 ## 什么是 IaC? 基础设施即代码(Infrastructure as Code)是用代码定义和管理基础设施的实践。Terraform 是最流行的 IaC 工具,支持多云平台。 ## 安装与初始化 ```bash # macOS brew install terraform # 验证安装 terraform version # 初始化项目 mkdir my-infra && cd my-infra terraform init ``` ## Provider 配置 ```hcl # main.tf terraform { required_version = ">= 1.0" required_providers { aws = { source = "hashicorp/aws" version = "~> 5.0" } } } provider "aws" { region = var.aws_region } ``` ## 定义资源 ```hcl # vpc.tf resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" enable_dns_hostnames = true enable_dns_support = true tags = { Name = "main-vpc" Environment = var.environment } } resource "aws_subnet" "public" { count = 2 vpc_id = aws_vpc.main.id cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 8, count.index) availability_zone = data.aws_availability_zones.available.names[count.index] map_public_ip_on_launch = true tags = { Name = "public-subnet-${count.index + 1}" } } resource "aws_security_group" "web" { name = "web-sg" vpc_id = aws_vpc.main.id ingress { from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } ingress { from_port = 443 to_port = 443 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } } ``` ## 变量与输出 ```hcl # variables.tf variable "aws_region" { description = "AWS 区域" type = string default = "ap-southeast-1" } variable "environment" { description = "环境标识" type = string validation { condition = contains(["dev", "staging", "prod"], var.environment) error_message = "环境必须是 dev, staging 或 prod" } } variable "instance_type" { description = "EC2 实例类型" type = string default = "t3.micro" } # outputs.tf output "vpc_id" { value = aws_vpc.main.id description = "VPC ID" } output "public_subnet_ids" { value = aws_subnet.public[*].id } ``` ## 模块化 ```hcl # modules/ec2/main.tf variable "instance_type" { type = string } variable "subnet_id" { type = string } variable "sg_ids" { type = list(string) } resource "aws_instance" "this" { ami = data.aws_ami.amazon_linux.id instance_type = var.instance_type subnet_id = var.subnet_id vpc_security_group_ids = var.sg_ids } output "public_ip" { value = aws_instance.this.public_ip } # 使用模块 module "web_server" { source = "./modules/ec2" instance_type = "t3.small" subnet_id = aws_subnet.public[0].id sg_ids = [aws_security_group.web.id] } ``` ## 核心命令 ```bash terraform init # 初始化(下载 Provider) terraform plan # 预览变更 terraform apply # 应用变更 terraform destroy # 销毁所有资源 terraform fmt # 格式化代码 terraform validate # 语法检查 ``` ## 最佳实践 1. 使用远程状态存储(S3 + DynamoDB) 2. 将通用资源封装为模块 3. 使用 `terraform plan` 预览后再 apply 4. 敏感变量用 `sensitive = true` 标记 5. 用 `.tfvars` 文件管理不同环境的变量