title: Conditionals in for_each loop around elastic IPs
body: <p>I have the following code and I would like to have a conditional that will only create an elastic IP if the instance is part of a public subnet (or based off of a boolean value if needed).  This is the code that I currently have that works, but I want it to not create elastic IPs for resources on the private subnets:</p>
  <pre><code>locals {
    instances_beta = {
      my-ec2 = {
        name           = &quot;myec2&quot;,
        ami            = &quot;ami-029e27fb2fc8ce9d8&quot;,
        instancetype   = &quot;t3.xlarge&quot;
        environment    = &quot;Beta&quot;,
        securitygroups = [var.mysg],
        subnetid       = var.public-a,
        elasticip      = true
      }
    }
  }
  
  resource &quot;aws_instance&quot; &quot;beta-instance&quot; {
    for_each               = local.instances_beta
    ami                    = each.value.ami
    instance_type          = each.value.instancetype
    subnet_id              = each.value.subnetid
    key_name               = &quot;mykey&quot;
    vpc_security_group_ids = each.value.securitygroups
  
    tags = {
      Name        = each.value.name
      Environment = each.value.environment
    }
  }
  
  resource &quot;aws_eip&quot; &quot;beta-eip&quot; {
    for_each = local.instances_beta
    instance = aws_instance.beta-instance[each.key].id
    vpc      = true
  }
  </code></pre>
  <p>It sounds like count is the best way to do something like that, but I cannot do that as I am already using a for_each to achieve the resource creation.  I was trying to do this with a nested for loop, but I cannot quite figure out how to get the syntax correct or if this is the best way to do it.  For reference , the best resource I found on it was here around for_each conditionals: <a href="https://blog.gruntwork.io/terraform-tips-tricks-loops-if-statements-and-gotchas-f739bbae55f9" rel="nofollow noreferrer">https://blog.gruntwork.io/terraform-tips-tricks-loops-if-statements-and-gotchas-f739bbae55f9</a></p>