3-创建多台ECS并绑定弹性公网IP

上一篇文章演示了创建一台服务器和EIP并把EIP绑定到服务器上。如果我需要创建多台服务器和多个EIP,然后分别把EIP绑定到服务器上,该怎么写呢?

直接上配置

terraform {
  required_providers {
    alicloud = {
      source  = "aliyun/alicloud"
      version = ">= 1.200.0"
    }
  }
  required_version = ">= 1.1.0"
}

provider "alicloud" {
  region     = "cn-beijing"
  access_key = "LTAI5tHoKTbsrygy"   # 替换成你的 Access Key
  secret_key = "VM3BioB6DzgESQ0"    # 替换成你的 Secret Key
}

# 变量:创建 ECS 的数量
variable "ecs_count" {
  default = 3
}

# 创建 ECS 实例
resource "alicloud_instance" "ecs" {
  count           = var.ecs_count
  instance_name   = "my-ecs-${count.index + 1}"
  image_id        = "ubuntu_24_04_x64_20G_alibase_20250722.vhd"
  instance_type   = "ecs.t5-lc1m1.small"
  security_groups = ["sg-2zegke7sqqv0vqv7k"]
  vswitch_id      = "vsw-2zeo9oxtwaa2rvjw9"
  internet_max_bandwidth_out = 0
}

# 创建 EIP
resource "alicloud_eip" "eip" {
  count = var.ecs_count
  bandwidth             = 5
  internet_charge_type  = "PayByTraffic"
}

# 绑定 ECS 和 EIP
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
}

# 输出 ECS 私网 IP
output "ecs_private_ips" {
  value = [for i in alicloud_instance.ecs : i.private_ip]
}

# 输出 ECS 公网 IP(EIP)
output "ecs_public_ips" {
  value = [for i in alicloud_eip.eip : i.ip_address]
}

 

posted @ 2025-09-10 14:22  羊脂玉净瓶  阅读(5)  评论(0)    收藏  举报