Select subnet_id 在跨 4 个 AZ 部署多个实例时匹配 AZ

Select subnet_id in matching AZ when deploying multiple instances across 4 AZs

我有一个资源块,它在现有 VPC 中创建了 4 个额外的子网:

# Create a subnet to launch instances into resource 

"aws_subnet" "mesos_subnet" { 
   vpc_id = "${var.dcos_vpc}" 
   count = 4 
   cidr_block = "${cidrsubnet(var.subnet_range, 4,   count.index)}"
   availability_zone = "${element(split(",", lookup(var.azs, var.region)), count.index)}"     
  map_public_ip_on_launch = true 
  tags { "Name" = "${var.prefix}-${element(split(",", lookup(var.azs,   var.region)), 
 count.index)}-sn" } 

}

并且我正在使用这样的资源块创建实例,它会将实例分布在可用的 AZ(该区域中有 4 个):

resource "aws_instance" "agents" {
instance_type = "m4.2xlarge"
ami = "${lookup(var.amis, var.region)}"
count = "${var.agent_instance_count}"
key_name = "${var.key_name}"
vpc_security_group_ids = ["${aws_security_group.internal_sg.id}","${aws_security_group.admin_sg.id   }"]
   associate_public_ip_address = true
   iam_instance_profile =    "${aws_iam_instance_profile.agent_profile.name}"
    availability_zone = "${element(split(",", lookup(var.azs,     var.region)), count.index)}"
   subnet_id = "${element(aws_subnet.dcos_subnet.*.id, count.index)}"
    tags {
      Name = "${var.prefix}-mesos-agent-${count.index}"
      owner = "${var.owner}"
    expiration = "${var.expiration}"
  }
  }

但是,在子网中 select 或者对于实例创建,我似乎无法在具有匹配 AZ 的子网中创建实例,即, terraform 尝试在子网中创建实例,但与正确的 AZ 不匹配。所以我在申请时收到此错误:

 * aws_instance.agents.3: Error launching source instance:    InvalidParameterValue: Value (eu-west-1a) for parameter availabilityZone   is invalid. Subnet 'subnet-xxxxxx' is in the availability zone eu-west-1b
         status code: 400, request id: 26665eee-071b-4ca1-a96b-  19b22c2fff94
 * aws_instance.agents.4: Error launching source instance:    InvalidParameterValue: Value (eu-west-1b) for parameter availabilityZone   is invalid. Subnet 'subnet-yyyyyyyy' is in the availability zone eu-west-  1a

我想我需要一个 select 语句,它可以以某种方式过滤掉和 select 对应于 AZ 的子网 ID(创建的子网的) select编辑于:

 "availability_zone = "${element(split(",", lookup(var.azs, var.region)), count.index)}"".

有人知道我该怎么做吗?

如果您只是分配 subnet_id,该实例将被放置到(那个子网的)适当的可用区中。无需为 aws_instance 资源分配 subnet_idavailability_zone 属性。这两个属性都是可选的。只使用一个(子网)就足够了。