7-多环境配置示例
下面整理一个 多环境(dev / prod)Terraform 配置结构,这样只需要切换变量文件就能在不同环境创建 ECS + EIP。
目录结构
project/
├── main.tf
├── variables.tf
├── outputs.tf
├── dev.tfvars
└── prod.tfvars
main.tf
terraform {
required_providers {
alicloud = {
source = "aliyun/alicloud"
version = ">= 1.200.0"
}
}
required_version = ">= 1.1.0"
}
provider "alicloud" {
region = var.region
access_key = var.access_key
secret_key = var.secret_key
}
# 创建多台 ECS 实例
resource "alicloud_instance" "ecs" {
count = var.ecs_count
instance_name = "${var.env_name}-ecs-${count.index + 1}"
image_id = var.image_id
instance_type = var.instance_type
security_groups = [var.security_group_id]
vswitch_id = var.vswitch_id
internet_max_bandwidth_out = 0
}
# 创建多个 EIP
resource "alicloud_eip" "eip" {
count = var.ecs_count
bandwidth = 5
internet_charge_type = "PayByTraffic"
}
# 绑定 EIP 到 ECS
resource "alicloud_eip_association" "assoc" {
count = var.ecs_count
instance_id = alicloud_instance.ecs[count.index].id
allocation_id = alicloud_eip.eip[count.index].id
}
variables.tf
variable "region" {
type = string
description = "Region of ECS"
}
variable "access_key" {
type = string
description = "Access key"
}
variable "secret_key" {
type = string
description = "Secret key"
}
variable "ecs_count" {
type = number
description = "Number of ECS instances"
}
variable "image_id" {
type = string
description = "Image ID"
}
variable "instance_type" {
type = string
description = "ECS instance type"
}
variable "security_group_id" {
type = string
description = "Security group ID"
}
variable "vswitch_id" {
type = string
description = "VSwitch ID"
}
variable "env_name" {
type = string
description = "Environment name, e.g. dev/prod"
}
outputs.tf
output "private_ips" {
value = [for i in alicloud_instance.ecs : i.private_ip]
}
output "public_ips" {
value = [for e in alicloud_eip.eip : e.ip_address]
}
dev.tfvars
region = "cn-beijing"
access_key = "你的AK"
secret_key = "你的SK"
ecs_count = 1
image_id = "ubuntu_24_04_x64_20G_alibase_20250722.vhd"
instance_type = "ecs.t5-lc1m1.small"
security_group_id = "sg-devxxxxx"
vswitch_id = "vsw-devxxxxx"
env_name = "dev"
prod.tfvars
region = "cn-beijing"
access_key = "你的AK"
secret_key = "你的SK"
ecs_count = 3
image_id = "ubuntu_24_04_x64_20G_alibase_20250722.vhd"
instance_type = "ecs.g6.large"
security_group_id = "sg-proxxxxx"
vswitch_id = "vsw-proxxxxx"
env_name = "prod"
使用方式: