EC2实例创建

问题描述:

我正在尝试创建多个EC2实例,但是它们具有不同的AMI,实例类型,并且应位于不同的可用区中,如下所示.我尝试了几种不同的方法,但无法使其正常工作.

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"
    }
  }
}

如果要使用 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
  }
}