Terraform 是由 HashiCorp 于 2014 年创建的开源基础设施即代码(IaC)工具,由 Mitchell Hashimoto 和 Armon Dadgar 设计。Terraform 使用声明式配置语言(HCL)来描述和管理云资源。
Terraform 的核心定位是 基础设施即代码的标准工具。它提供了:
HashiCorp 于 2014 年发布 Terraform,旨在解决多云环境中基础设施管理的复杂性。Terraform 从 Vagrant 和 Packer 等工具的经验中汲取灵感,提出了 声明式基础设施即代码 的理念。
# main.tf - Terraform 配置文件
# Provider 配置
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
# 配置 AWS Provider
provider "aws" {
region = "us-west-2"
}
# 创建 VPC
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
enable_dns_hostnames = true
tags = {
Name = "my-vpc"
}
}
# 创建子网
resource "aws_subnet" "main" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.1.0/24"
tags = {
Name = "my-subnet"
}
}
# 创建安全组
resource "aws_security_group" "web" {
name = "web-sg"
description = "Web server security group"
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"]
}
tags = {
Name = "web-sg"
}
}
# 创建 EC2 实例
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
subnet_id = aws_subnet.main.id
vpc_security_group_ids = [aws_security_group.web.id]
user_data = <<-EOF
#!/bin/bash
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "<h1>Hello from Terraform!</h1>" > /var/www/html/index.html
EOF
tags = {
Name = "web-server"
}
}
# 输出变量
output "public_ip" {
value = aws_instance.web.public_ip
}
output "public_dns" {
value = aws_instance.web.public_dns
}
# variables.tf
variable "region" {
description = "AWS region"
type = string
default = "us-west-2"
}
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t2.micro"
}
variable "environment" {
description = "Environment name"
type = string
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "Environment must be dev, staging, or prod."
}
}
# terraform.tfvars
region = "us-east-1"
instance_type = "t3.medium"
environment = "prod"
# 使用官方模块
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "5.0.0"
name = "my-vpc"
cidr = "10.0.0.0/16"
azs = ["us-west-2a", "us-west-2b", "us-west-2c"]
private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
public_subnets = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]
enable_nat_gateway = true
enable_vpn_gateway = true
tags = {
Terraform = "true"
Environment = "dev"
}
}
# 使用模块输出
output "vpc_id" {
value = module.vpc.vpc_id
}
output "public_subnets" {
value = module.vpc.public_subnets
}
# 数据源(读取现有资源)
data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-22.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
owners = ["099720109477"] # Canonical
}
# 使用数据源
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
# 生命周期策略
lifecycle {
create_before_destroy = true
prevent_destroy = false
ignore_changes = [ami, user_data]
}
# 依赖管理
depends_on = [
aws_security_group.web,
aws_subnet.main
]
}
# 远程状态存储(S3 + DynamoDB)
# backend.tf
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-west-2"
encrypt = true
dynamodb_table = "terraform-locks"
}
}
# 远程状态存储(Azure)
terraform {
backend "azurerm" {
resource_group_name = "terraform-state"
storage_account_name = "tfstate1234"
container_name = "tfstate"
key = "prod.terraform.tfstate"
}
}
# 远程状态存储(GCP)
terraform {
backend "gcs" {
bucket = "terraform-state-bucket"
prefix = "prod"
}
}
# 初始化
terraform init
# 格式化代码
terraform fmt
# 验证配置
terraform validate
# 查看执行计划
terraform plan
# 应用变更
terraform apply
terraform apply -auto-approve # 跳过确认
# 销毁资源
terraform destroy
# 查看状态
terraform show
terraform state list
terraform state show aws_instance.web
# 输出变量
terraform output
# 刷新状态
terraform refresh
# 导入现有资源
terraform import aws_instance.web i-1234567890abcdef0
| 对比项 | Terraform | CloudFormation | Ansible | Pulumi |
|---|---|---|---|---|
| 类型 | 声明式 IaC | 声明式 IaC | 配置管理 | 代码式 IaC |
| 多云支持 | ✅ 300+ | ❌ 仅 AWS | ✅ 有限 | ✅ 丰富 |
| 语言 | HCL | JSON/YAML | YAML | TypeScript/Python/Go |
| 状态管理 | ✅ 核心 | ✅ 核心 | ❌ | ✅ 核心 |
| 学习曲线 | 中等 | 陡峭 | 平缓 | 中等 |
| 适用场景 | 基础设施编排 | AWS 专用 | 配置管理 | 编程式 IaC |
HCL 语法、Provider 配置、基本资源创建(EC2/VPC)
变量、输出、数据源、生命周期、远程状态管理
模块化、条件表达式、循环、动态块、工作空间
多云部署、CI/CD 集成、团队协作、状态安全
Terraform 是云原生的"基础设施编译器"。
它用 声明式配置、不可变基础设施、多云支持 让基础设施管理变得可版本控制、可审查、可回滚。Terraform 是 DevOps 工程师的必修课。
掌握 Terraform,意味着你能 高效管理云资源、自动化基础设施部署、实现环境一致性。
"Terraform 让基础设施像代码一样优雅。" 🏗️