什么是 Terraform

Terraform 简介

Terraform 是由 HashiCorp 开发的开源基础设施即代码(Infrastructure as Code,IaC)工具。它允许你使用声明式配置文件来定义和管理云基础设施和服务。

核心概念

基础设施即代码(IaC)

  • 使用代码来定义基础设施
  • 版本控制和协作
  • 可重复、可审计的部署
  • 自动化基础设施管理

Terraform 的特点

1. 声明式语法

# 声明你想要的状态,Terraform 会自动计算如何达到
resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  
  tags = {
    Name = "Web Server"
  }
}

2. 多云支持

  • AWS、Azure、GCP
  • Alibaba Cloud、华为云、腾讯云
  • VMware、OpenStack
  • Kubernetes、Docker
  • 200+ Provider 支持

3. 执行计划

# 预览变更,不会立即执行
terraform plan

# Plan: 3 to add, 2 to change, 1 to destroy.

4. 资源图

  • 自动管理资源依赖
  • 并行创建独立资源
  • 正确的创建和销毁顺序

5. 状态管理

  • 跟踪真实基础设施状态
  • 映射配置到实际资源
  • 支持远程状态存储

为什么使用 Terraform

传统方式 vs Terraform

传统手动方式

# 1. 登录云控制台
# 2. 点击"创建实例"
# 3. 填写表单(实例类型、网络、存储...)
# 4. 等待创建完成
# 5. 手动配置安全组
# 6. 记录实例 IP 和配置

问题

  • ❌ 手动操作容易出错
  • ❌ 难以重复和复制
  • ❌ 无法版本控制
  • ❌ 缺乏协作机制
  • ❌ 配置漂移难以发现

Terraform 方式

# main.tf - 一次编写,随处部署
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  
  vpc_security_group_ids = [aws_security_group.web.id]
  
  tags = {
    Name        = "Web Server"
    Environment = "Production"
  }
}

resource "aws_security_group" "web" {
  name        = "web-sg"
  description = "Security group for web server"
  
  ingress {
    from_port   = 80
    to_port     = 80
    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"]
  }
}

优势

  • ✅ 代码化,可版本控制
  • ✅ 可重复部署
  • ✅ 自动管理依赖
  • ✅ 团队协作友好
  • ✅ 预览变更,降低风险

Terraform 工作流程

┌─────────────────────────────────────────────────────────┐
│ 1. Write(编写)                                         │
│    编写 .tf 配置文件定义基础设施                         │
└────────────────┬────────────────────────────────────────┘
                 │
                 ▼
┌─────────────────────────────────────────────────────────┐
│ 2. Init(初始化)                                        │
│    terraform init                                       │
│    - 下载 Provider 插件                                  │
│    - 初始化后端配置                                      │
│    - 准备工作目录                                        │
└────────────────┬────────────────────────────────────────┘
                 │
                 ▼
┌─────────────────────────────────────────────────────────┐
│ 3. Plan(计划)                                          │
│    terraform plan                                       │
│    - 读取配置文件                                        │
│    - 刷新当前状态                                        │
│    - 生成执行计划                                        │
│    - 显示将要执行的变更                                  │
└────────────────┬────────────────────────────────────────┘
                 │
                 ▼
┌─────────────────────────────────────────────────────────┐
│ 4. Apply(应用)                                         │
│    terraform apply                                      │
│    - 执行计划中的变更                                    │
│    - 创建/更新/删除资源                                  │
│    - 更新状态文件                                        │
└────────────────┬────────────────────────────────────────┘
                 │
                 ▼
┌─────────────────────────────────────────────────────────┐
│ 5. Destroy(销毁,可选)                                 │
│    terraform destroy                                    │
│    - 删除所有管理的资源                                  │
│    - 清理基础设施                                        │
└─────────────────────────────────────────────────────────┘

第一个 Terraform 示例

创建一个 AWS EC2 实例:

1. 安装 Terraform

# macOS
brew install terraform

# Linux
wget https://releases.hashicorp.com/terraform/1.6.0/terraform_1.6.0_linux_amd64.zip
unzip terraform_1.6.0_linux_amd64.zip
sudo mv terraform /usr/local/bin/

# 验证安装
terraform version

2. 创建配置文件 main.tf

terraform {
  required_version = ">= 1.0"
  
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  
  tags = {
    Name = "My First Terraform Instance"
  }
}

3. 初始化项目

terraform init

输出:

Initializing the backend...
Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 5.0"...
- Installing hashicorp/aws v5.31.0...
- Installed hashicorp/aws v5.31.0

Terraform has been successfully initialized!

4. 查看执行计划

terraform plan

输出:

Terraform will perform the following actions:

  # aws_instance.example will be created
  + resource "aws_instance" "example" {
      + ami                          = "ami-0c55b159cbfafe1f0"
      + instance_type                = "t2.micro"
      + tags                         = {
          + "Name" = "My First Terraform Instance"
        }
      # ... (other computed attributes)
    }

Plan: 1 to add, 0 to change, 0 to destroy.

5. 应用配置

terraform apply

输出:

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_instance.example: Creating...
aws_instance.example: Still creating... [10s elapsed]
aws_instance.example: Creation complete after 15s [id=i-0123456789abcdef0]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

6. 查看状态

terraform show

7. 销毁资源

terraform destroy

Terraform vs 其他工具

Terraform vs Ansible

特性 Terraform Ansible
类型 基础设施即代码 配置管理
语法 HCL(声明式) YAML(过程式)
最佳用途 创建和管理基础设施 配置和管理软件
状态管理 有(状态文件)
幂等性 自动保证 需要手动编写
云支持 原生多云支持 通过模块支持

使用场景

  • Terraform:创建 VPC、EC2、RDS、负载均衡器等基础设施
  • Ansible:安装软件、配置服务、部署应用

最佳实践:结合使用

# Terraform 创建基础设施
resource "aws_instance" "web" {
  ami           = "ami-xxx"
  instance_type = "t2.micro"
  
  # 使用 Ansible 配置
  provisioner "local-exec" {
    command = "ansible-playbook -i '${self.public_ip},' playbook.yml"
  }
}

Terraform vs CloudFormation

特性 Terraform AWS CloudFormation
云支持 多云(AWS、Azure、GCP等) 仅 AWS
语法 HCL JSON/YAML
状态管理 显式状态文件 AWS 管理
学习曲线 中等 中等
社区 活跃,第三方 Provider 丰富 AWS 官方支持

核心组件

1. Provider(提供商)

连接云平台或服务的插件:

# AWS Provider
provider "aws" {
  region     = "us-east-1"
  access_key = var.aws_access_key
  secret_key = var.aws_secret_key
}

# Azure Provider
provider "azurerm" {
  features {}
}

# Kubernetes Provider
provider "kubernetes" {
  config_path = "~/.kube/config"
}

2. Resource(资源)

基础设施组件:

resource "aws_instance" "web" {
  ami           = "ami-xxx"
  instance_type = "t2.micro"
}

resource "aws_s3_bucket" "data" {
  bucket = "my-data-bucket"
}

3. Data Source(数据源)

查询现有资源:

data "aws_ami" "ubuntu" {
  most_recent = true
  owners      = ["099720109477"]
  
  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
  }
}

resource "aws_instance" "web" {
  ami = data.aws_ami.ubuntu.id
  # ...
}

4. Variable(变量)

参数化配置:

variable "instance_type" {
  description = "EC2 instance type"
  type        = string
  default     = "t2.micro"
}

resource "aws_instance" "web" {
  instance_type = var.instance_type
  # ...
}

5. Output(输出)

导出值:

output "instance_ip" {
  description = "Public IP of the instance"
  value       = aws_instance.web.public_ip
}

适用场景

✅ 适合使用 Terraform

  1. 多云环境管理

    • 同时管理 AWS、Azure、GCP 资源
    • 避免云厂商锁定
  2. 基础设施标准化

    • 开发、测试、生产环境一致性
    • 快速复制环境
  3. 团队协作

    • 代码审查基础设施变更
    • Git 版本控制
  4. 大规模基础设施

    • 管理数百个资源
    • 自动化部署和更新
  5. 灾难恢复

    • 快速重建基础设施
    • 文档化的基础设施

❌ 不适合使用 Terraform

  1. 应用程序部署

    • 使用 Kubernetes、Docker Compose
    • CI/CD 工具更合适
  2. 临时测试

    • 频繁变更的实验环境
    • 云控制台可能更快
  3. 极度动态的场景

    • 需要实时响应的自动扩缩容
    • 使用云原生工具(如 Kubernetes HPA)

学习路径

入门阶段
  ├─ Terraform 基础概念
  ├─ HCL 语法
  ├─ 基本命令(init、plan、apply、destroy)
  └─ 简单资源创建

进阶阶段
  ├─ 变量和输出
  ├─ 模块化设计
  ├─ 状态管理
  ├─ 工作空间
  └─ 远程状态

高级阶段
  ├─ 自定义 Provider
  ├─ 复杂依赖管理
  ├─ CI/CD 集成
  ├─ 安全最佳实践
  └─ 企业级架构设计

总结

Terraform 是现代云基础设施管理的标准工具:

  • 声明式:描述想要的状态,而非如何达到
  • 多云:统一的语法管理不同云平台
  • 版本控制:基础设施变更可追溯
  • 协作友好:团队协作和代码审查
  • 自动化:减少人为错误,提高效率

开始学习 Terraform,掌握现代 IaC 技能!


下一章Terraform 安装和环境准备