Infrastructure as Code

Terraform Examples

覆盖 AWS / GCP / Aliyun / vSphere 四大平台的生产级 Terraform 示例, 包含计算、网络、负载均衡等常见场景的最小可运行配置。

◦ 6 个模块 ◦ 4 个云平台 ◦ Terraform ≥ 1.0

模块总览

点击「查看代码」跳转到对应模块的完整示例。

AW

EC2 实例

Ubuntu 24.04 LTS + 弹性 IP + 安全组(SSH)+ S3 远端 State

aws_instance aws_eip aws_security_group gp3 1TB c5.2xlarge
AW

ALB 负载均衡

HTTPS 监听器 + 目标组 + 健康检查 + CORS 响应头 + 主机路由

aws_lb aws_lb_listener aws_lb_target_group HTTPS/443 4 AZ
GC

GCE 实例

GCE 虚拟机 + 静态外部 IP + 防火墙规则 + Shielded VM + GCS 后端

google_compute_instance google_compute_address google_compute_firewall pd-ssd e2-medium
GC

HTTP(S) 负载均衡

全局 HTTPS 转发 + URL Map + 后端服务 + 健康检查 + CORS 策略

google_compute_url_map google_compute_target_https_proxy google_compute_backend_service global forwarding
AL

ECS 实例

阿里云 ECS + 弹性公网 IP + 安全组 + ESSD 加密云盘 + 包月自动续费

alicloud_instance alicloud_eip_address alicloud_security_group cloud_essd PrePaid
vS

vSphere 虚拟机

Cloud Image 模板克隆 + cloud-init 注入(静态 IP / 包安装 / node_exporter)+ 热添加 CPU/内存

vsphere_virtual_machine cloud-init guestinfo node_exporter hot add

aws/ec2/main.tf

← 返回
# ==============================================================================
# AWS EC2 示例:Ubuntu 24.04 实例 + 弹性 IP + 安全组
# ==============================================================================

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "6.8.0"
    }
  }

  backend "s3" {
    bucket = ""  # <-- 替换为 S3 bucket
    key    = "aws/ec2/terraform.tfstate"
    region = "auto"
    endpoints = { s3 = "" }
  }
}

provider "aws" {
  profile = ""
  region  = ""
}

# 查询最新 Ubuntu 24.04 AMI
data "aws_ami" "ubuntu_2404" {
  most_recent = true
  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"]
  }
  owners = ["099720109477"]
}

# 安全组:放行 SSH 22
resource "aws_security_group" "ssh" {
  name   = "allow-ssh"
  vpc_id = data.aws_vpc.this.id
}

# EC2 实例
resource "aws_instance" "this" {
  ami           = data.aws_ami.ubuntu_2404.id
  instance_type = "c5.2xlarge"
  monitoring    = true

  root_block_device {
    volume_size = 1024
    volume_type = "gp3"
  }

  vpc_security_group_ids = [aws_security_group.ssh.id]
}

aws/alb/main.tf

← 返回
# ==============================================================================
# AWS ALB 示例:HTTPS 监听器 + 目标组 + 健康检查
# ==============================================================================

# Application Load Balancer(跨 4 个 AZ)
resource "aws_lb" "this" {
  name               = "alb-example"
  internal           = false
  load_balancer_type = "application"
  security_groups    = [aws_security_group.alb.id]
  subnets = [
    data.aws_subnet.az_a.id,
    data.aws_subnet.az_b.id,
    data.aws_subnet.az_c.id,
    data.aws_subnet.az_d.id,
  ]
  enable_deletion_protection = true
}

# 目标组(IP 类型,健康检查路径 /)
resource "aws_lb_target_group" "this" {
  name        = "app-backend"
  port        = 8080
  protocol    = "HTTP"
  target_type = "ip"
  vpc_id      = data.aws_vpc.this.id

  health_check {
    enabled  = true
    interval = 5
    path     = "/"
    port     = 8080
    matcher  = "200-299"
  }
}

# HTTPS 监听器 + 内置 CORS 响应头
resource "aws_lb_listener" "https" {
  load_balancer_arn = aws_lb.this.arn
  port              = 443
  protocol          = "HTTPS"
  ssl_policy        = "ELBSecurityPolicy-TLS13-1-2-Res-2021-06"
  certificate_arn   = ""  # <-- ACM 证书 ARN

  routing_http_response_access_control_allow_origin_header_value  = "*"
  routing_http_response_access_control_allow_methods_header_value = "GET, POST, OPTIONS"

  default_action {
    type = "forward"
    forward {
      target_group { arn = aws_lb_target_group.this.arn }
    }
  }
}

gcp/compute/main.tf

← 返回
# ==============================================================================
# GCP Compute 示例:GCE 实例 + 静态 IP + 防火墙
# ==============================================================================

terraform {
  required_version = ">= 1.0"

  backend "gcs" {
    bucket = ""
    prefix = "gcp/compute/terraform.tfstate"
  }
}

provider "google" {
  project = ""
}

# 防火墙:仅放行 SSH,通过 target_tags 精准控制
resource "google_compute_firewall" "ssh" {
  name    = "allow-ssh"
  network = data.google_compute_network.default.name

  allow {
    protocol = "tcp"
    ports    = ["22"]
  }

  source_ranges = ["0.0.0.0/0"]
  target_tags   = ["allow-ssh"]
}

# GCE 实例 + Shielded VM
resource "google_compute_instance" "this" {
  name         = "gce-example"
  machine_type = "e2-medium"
  zone         = "us-west1-a"
  tags         = ["terraform", "allow-ssh"]

  boot_disk {
    initialize_params {
      image = data.google_compute_image.ubuntu_2204.self_link
      type  = "pd-ssd"
      size  = 50
    }
  }

  shielded_instance_config {
    enable_integrity_monitoring = true
    enable_vtpm                 = true
  }
}

gcp/loadbalancing/main.tf

← 返回
# ==============================================================================
# GCP HTTP(S) 负载均衡示例:全局转发 + URL Map + CORS
# ==============================================================================

# 全局 HTTPS 转发规则
resource "google_compute_global_forwarding_rule" "https" {
  name       = "lb-forwarding-rule"
  ip_address = google_compute_global_address.this.address
  port_range  = "443"
  ip_protocol = "TCP"
  target      = google_compute_target_https_proxy.this.id
}

# URL Map:HTTP 自动跳转 HTTPS + 按域名路由
resource "google_compute_url_map" "this" {
  name = "lb-url-map"

  default_url_redirect {
    https_redirect = true
  }

  host_rule {
    hosts        = [""]  # <-- 你的域名
    path_matcher = "backend"
  }

  path_matcher {
    name            = "backend"
    default_service = google_compute_backend_service.this.id

    path_rule {
      paths   = ["/*"]
      service = google_compute_backend_service.this.id
      route_action {
        cors_policy {
          allow_origins = ["*"]
          allow_methods = ["GET", "POST", "OPTIONS"]
        }
      }
    }
  }
}

aliyun/ecs/main.tf

← 返回
# ==============================================================================
# 阿里云 ECS 示例:包月实例 + EIP + ESSD 加密云盘
# ==============================================================================

terraform {
  required_providers {
    alicloud = {
      source  = "aliyun/alicloud"
      version = "1.273.0"
    }
  }
}

provider "alicloud" {
  region = "cn-beijing"
}

# 弹性公网 IP(BGP,按流量计费)
resource "alicloud_eip_address" "this" {
  isp                  = "BGP"
  bandwidth            = 200
  internet_charge_type = "PayByTraffic"
}

# ECS 实例(包月,自动续费,删除保护)
resource "alicloud_instance" "this" {
  instance_name = "ecs-example"
  instance_type = "ecs.c9.large"

  system_disk_category  = "cloud_essd"
  system_disk_size      = 100
  system_disk_encrypted = true

  instance_charge_type = "PrePaid"
  period               = 1
  period_unit          = "Month"
  renewal_status       = "AutoRenewal"
  deletion_protection  = true
}

vsphere/vm/main.tf

← 返回
# ==============================================================================
# vSphere 示例:Cloud Image 模板克隆 + cloud-init 注入
# ==============================================================================

terraform {
  required_providers {
    vsphere = {
      source  = "vmware/vsphere"
      version = "2.15.0"
    }
  }
}

provider "vsphere" {
  user                 = ""  # <-- administrator@vsphere.local
  password             = ""
  vsphere_server       = ""  # <-- vcenter.example.com
  allow_unverified_ssl = true
}

# 指定 ESXi 物理主机(裸机部署)
data "vsphere_host" "this" {
  name          = ""  # <-- ESXi IP
  datacenter_id = data.vsphere_datacenter.this.id
}

# Cloud Image 模板(需提前导入 vCenter)
data "vsphere_virtual_machine" "template" {
  name          = ""  # <-- ubuntu-noble-24.04-cloudimg
  datacenter_id = data.vsphere_datacenter.this.id
}

resource "vsphere_virtual_machine" "this" {
  name             = ""  # <-- vm-monitor-00
  resource_pool_id = data.vsphere_host.this.resource_pool_id
  datastore_id     = data.vsphere_datastore.this.id
  guest_id         = data.vsphere_virtual_machine.template.guest_id
  num_cpus         = 2
  memory           = 4096

  # 热添加 CPU / 内存
  cpu_hot_add_enabled    = true
  memory_hot_add_enabled = true

  clone {
    template_uuid = data.vsphere_virtual_machine.template.id
  }

  network_interface {
    network_id = data.vsphere_network.this.id
  }

  disk {
    label = "disk0"
    size  = 100
  }

  # cloud-init 注入(base64 编码后传入)
  extra_config = {
    "guestinfo.userdata"          = ""  # <-- userdata.b64
    "guestinfo.userdata.encoding" = "base64"
    "guestinfo.metadata"          = ""  # <-- metadata.b64
    "guestinfo.metadata.encoding" = "base64"
  }
}

快速上手

三步启动任意模块。

Step 1

进入目标目录

选择你想要部署的云平台模块

cd aws/ec2
Step 2

填写占位值

编辑 main.tf,替换 <-- 标记的占位参数

vim main.tf
Step 3

执行部署

初始化、预览变更、应用

terraform init && terraform plan && terraform apply

运维提示

  • 生产环境务必使用远端 State(S3 / GCS)并启用状态锁定,避免多人并发写入冲突
  • 每次 terraform apply 前先执行 terraform plan 并仔细审查变更摘要
  • 为所有资源统一打上标签(tags / labels),便于计费归属和批量管理
  • 不要将凭据(AccessKey / Service Account Key)硬编码到 .tf 文件中,请使用环境变量或 Vault
  • 定期更新 Provider 版本,关注 Terraform Changelog