问题
I'm trying to create multiple EC2 instance but they have different AMIs, instance types and should be in different availability zones as shown below. I've tried a few different ways but can't make it work.
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"
}
}
}
回答1:
If you want to use count
, then it should be:
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
}
}
But with for_each
it could be:
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
}
}
来源:https://stackoverflow.com/questions/65664963/ec2-instance-creation