大家好,我是程序员柏风,AI 最全的 Vibecoding 学习地图 http://coderoadmap.cn 作者。
Terraform
这一课你将能做到
- 用 Terraform 定义 AWS 基础设施(EC2、S3、RDS)
- 理解 HCL 语法和状态管理
- 实现基础设施的版本控制和团队协作
为什么要学
手动在 AWS Console 点来点去,环境多了根本记不住。Terraform 用代码定义基础设施,一键创建、修改、销毁,环境可复现。
人话:Terraform 是「基础设施的施工图」,用代码画出你的云架构。
跟着做
步骤 1:安装与初始化
# 安装
brew install terraform # macOS
# 或下载 https://www.terraform.io/downloads
# 初始化项目
mkdir my-infra
cd my-infra
touch main.tf
步骤 2:第一个资源
# main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "web-server"
}
}
# 初始化
terraform init
# 预览变更
terraform plan
# 应用变更
terraform apply
# 销毁
terraform destroy
步骤 3:完整架构
# VPC
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "my-vpc"
}
}
# 公有子网
resource "aws_subnet" "public" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.1.0/24"
availability_zone = "us-east-1a"
tags = {
Name = "public-subnet"
}
}
# Internet Gateway
resource "aws_internet_gateway" "main" {
vpc_id = aws_vpc.main.id
}
# 路由表
resource "aws_route_table" "public" {
vpc_id = aws_vpc.main.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.main.id
}
}
resource "aws_route_table_association" "public" {
subnet_id = aws_subnet.public.id
route_table_id = aws_route_table.public.id
}
# 安全组
resource "aws_security_group" "web" {
name = "web-sg"
description = "Allow web traffic"
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"]
}
}
# EC2 实例
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
subnet_id = aws_subnet.public.id
vpc_security_group_ids = [aws_security_group.web.id]
tags = {
Name = "web-server"
}
}
步骤 4:变量与输出
# variables.tf
variable "instance_type" {
description = "EC2 instance type"
default = "t2.micro"
}
variable "environment" {
description = "Environment name"
default = "dev"
}
# main.tf
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = var.instance_type
tags = {
Name = "web-server"
Environment = var.environment
}
}
# outputs.tf
output "instance_ip" {
value = aws_instance.web.public_ip
}
# 使用变量
terraform apply -var="instance_type=t3.micro"
# 或使用文件
terraform apply -var-file="prod.tfvars"
步骤 5:远程状态
# backend.tf
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
}
}
面试常问
-
Terraform 和 CloudFormation 区别? Terraform 多云支持(AWS、Azure、GCP),CloudFormation 只支持 AWS。
-
如何管理多环境(dev/staging/prod)? 用 workspace 或目录结构分离,或用变量文件。
自测三问
terraform plan和apply的区别?- 为什么需要远程状态?
- 如何用变量实现多环境?
小结
Terraform 用代码定义基础设施,HCL 语法声明式,状态管理追踪资源。