覆盖 AWS / GCP / Aliyun / vSphere 四大平台的生产级 Terraform 示例, 包含计算、网络、负载均衡等常见场景的最小可运行配置。
点击「查看代码」跳转到对应模块的完整示例。
Ubuntu 24.04 LTS + 弹性 IP + 安全组(SSH)+ S3 远端 State
HTTPS 监听器 + 目标组 + 健康检查 + CORS 响应头 + 主机路由
GCE 虚拟机 + 静态外部 IP + 防火墙规则 + Shielded VM + GCS 后端
全局 HTTPS 转发 + URL Map + 后端服务 + 健康检查 + CORS 策略
阿里云 ECS + 弹性公网 IP + 安全组 + ESSD 加密云盘 + 包月自动续费
Cloud Image 模板克隆 + cloud-init 注入(静态 IP / 包安装 / node_exporter)+ 热添加 CPU/内存
# ============================================================================== # 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 示例: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 示例: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 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"] } } } } }
# ============================================================================== # 阿里云 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 示例: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" } }
三步启动任意模块。
选择你想要部署的云平台模块
cd aws/ec2
编辑 main.tf,替换 <-- 标记的占位参数
vim main.tf
初始化、预览变更、应用
terraform init && terraform plan && terraform apply
terraform apply 前先执行 terraform plan 并仔细审查变更摘要.tf 文件中,请使用环境变量或 Vault