Terraform 基础设施即代码
用代码定义和管理云基础设施。
4 小时
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"
}
}