0
votes

Im passing my modules a list and its going to create ec2 instances and eips and attach

Im using for_each so users can reorder the list and terraform wont try to destroy anything

BUT how do I use conditional resources now? Do I still use count? If so how because you cant use count with for_each.

This is my module now:

variable "mylist" {
  type            = set(string)
  description     = "Name used for tagging, AD, and chef"
}

variable "createip" {
  type            = bool
  default         = true
}

resource "aws_instance" "sdfsdfsdfsdf" {
  for_each    = var.mylist
  user_data   = data.template_file.user_data[each.key].rendered
  tags        = each.value
  ...

#conditional for EIP
resource "aws_eip" "public-ip" {
  for_each    = var.mylist
  // I cant use this anymore!
  // how can I say if true create else dont create
  #count       = var.createip ? 0 : length(tolist(var.mylist))
  instance = aws_instance.aws-vm[each.key].id
  vpc      = true
  tags     = each.value
}

I also need to get the value of the mylist item for eip too because I use that to tag the eip. So I think I need to index into the foreach loop somehow and also be able to use count or another list to determine if its created or not?

1

1 Answers

0
votes

I think I got it but I dont want to accept until its confirmed this is not the wrong way (not as a matter of opinion but improper usage that will cause actual problems)

variable "mylist" {
  type            = set(string)
  description     = "Name used for tagging, AD, and chef"
}

variable "createip" {
  type            = bool
  default         = true
}

locals {
  // set will-create-public-ip to empty array if false
  // otherwise use same mylist which module uses for creating instances
  will-create-public-ip = var.createip ? var.mylist : []
}

resource "aws_instance" "sdfsdfsdfsdf" {
  for_each    = var.mylist
  user_data   = data.template_file.user_data[each.key].rendered
  tags        = each.value
  ...

resource "aws_eip" "public-ip" {
  // will-create-public-ip set to mylist or empty to skip this resource creatation
  for_each    = will-create-public-ip
  instance = aws_instance.aws-vm[each.key].id
  vpc      = true
  tags     = each.value
}