EC2 instance creation

我与影子孤独终老i 提交于 2021-01-24 11:34:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!