我试图创建多个EC2实例,但它们有不同的AMI和实例类型,并且应该位于不同的可用性区域,如下所示。我尝试了几种不同的方法,但都无法成功。
locals {
az_ami = [
{Name = "host1", type = "t3a.medium", az = "eu_west_2a", ami_id = "ami-01234abc"},
{Name = "host2", type = "t3a.micro", az = "eu_west_2b", ami_id = "ami-01234def"},
{Name = "host3", type = "t3a.medium", az = "eu_west_2b", ami_id = "ami-01234gef"},
{Name = "host4", type = "t3a.medium", az = "eu_west_2a", ami_id = "ami-01234hty"}
]
}
#variable "ami_id" {}
resource "aws_instance" "myinstance" {
count = length(local.az_ami)
for_each = [{ for i in local.az_ami: }]
dynamic "ec2_instance"{
for_each = local.az_ami[count.index]
content {
instance_type = "ec2_instance.value.Name"
availability_zone = "ec2_instance.value.az"
ami = "ec2_instance.value.ami_id"
}
}
}
如果您想使用count
,那么它应该是:
resource "aws_instance" "myinstance" {
count = length(local.az_ami)
instance_type = local.az_ami[count.index].type
availability_zone = local.az_ami[count.index].az
ami = local.az_ami[count.index].ami_id
tags = {
Name = local.az_ami[count.index].Name
}
}
但有了for_each
,它可能是:
resource "aws_instance" "myinstance2" {
for_each = {for idx, val in local.az_ami: idx => val}
instance_type = each.value.type
availability_zone = each.value.az
ami = each.value.ami_id
tags = {
Name = each.value.Name
}
}