# For\_each null value

**URL:** <https://discuss.hashicorp.com/t/for-each-null-value/22253>\
**Category:** Terraform\
**Created:** [March 19, 2021, 9:22am UTC](https://discuss.hashicorp.com/t/for-each-null-value/22253 "2021-03-19T09:22:08Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![jprouten](https://avatars.discourse-cdn.com/v4/letter/j/d26b3c/32.png) [@jprouten](https://discuss.hashicorp.com/u/jprouten)\
**Post date:** [March 19, 2021, 9:22am UTC](https://discuss.hashicorp.com/t/for-each-null-value/22253/1 "2021-03-19T09:22:08Z")

</div>

I am currently creating a new Module that creates EC2’s. I have a simple fore\_each statement that works nicely. In the module I also need to allow the creation of multiple ENI’s. But these are optional so some EC2’s will not require extra ENI’s.

If I used count I could easily do this:

```auto
count = var.enable_dhcp_options ? 1 : 0

```

But I want to use a for\_each within the Resource so cannot use count. Is this possible?

```auto
locals {

  is_t_instance_type = replace(var.instance_type, "/^t(2|3|3a){1}\\..*$/", "1") == "1" ? true : false

}

resource "aws_instance" "this" {

  for_each = var.ec2

  ami = var.ami

  instance_type = var.instance_type

  

  vpc_security_group_ids = var.vpc_security_group_ids

  subnet_id = each.value["subnet"]

  private_ip = each.value["private_ip"]

  #user_data = var.user_data

  #user_data_base64 = var.user_data_base64

  key_name = var.key_name

  monitoring = var.monitoring

  get_password_data = var.get_password_data

  iam_instance_profile = var.iam_instance_profile

  associate_public_ip_address = var.associate_public_ip_address

  ebs_optimized = var.ebs_optimized

  disable_api_termination = var.disable_api_termination

  instance_initiated_shutdown_behavior = var.instance_initiated_shutdown_behavior

  placement_group = var.placement_group

  tenancy = var.tenancy

    credit_specification {

    cpu_credits = local.is_t_instance_type ? var.cpu_credits : null # move to var?

  }

}

#######

# ENI

#######

resource "aws_network_interface" "mgmt_eth" {

  for_each = var.ec2

  subnet_id = each.value["subnet_mgt"]

  security_groups = var.mgt_sg 

```

variables are set :

```auto
variable "ec2" {

  type = map(object({

    subnet = string

    name = string

    private_ip = string

      }))

}

variable "eni_mgt" {

  type = map(object({

    subnet_mgt = string

      }))

}

```

and module called:

```auto
module "ec2" {

  source = "../"

  ami = "ami-1234"

  instance_type = "t3.small"

  vpc_security_group_ids = ["sg-1234"]

  ec2 = {

    web1 = {

        name = "jpppp1"

        subnet = "subnet-1234"

        private_ip = ""

    },

    web2 = {

        name = "jpppp2"

        subnet = "subnet-5678"

        private_ip = ""

    }

}

eni_mgt = {

    web1 = {

        subnet_mgt = ""

    },

    web2 = {

        subnet_mgt = ""

    }

}

}

```

Using the above I expect 2 EC2’s (which work) and no mgmt\_eth. But it trys to create 2 mgmt\_eth.

```auto
# module.ec2.aws_network_interface.mgmt_eth["web2"] will be created
  + resource "aws_network_interface" "mgmt_eth" {
      + id = (known after apply)
      + ipv6_address_count = (known after apply)
      + ipv6_addresses = (known after apply)
      + mac_address = (known after apply)
      + outpost_arn = (known after apply)
      + private_dns_name = (known after apply)
      + private_ip = (known after apply)
      + private_ips = (known after apply)
      + private_ips_count = (known after apply)
      + security_groups = (known after apply)
      + source_dest_check = true

      + attachment {
          + attachment_id = (known after apply)
          + device_index = (known after apply)
          + instance = (known after apply)
        }
    }

```

I have tried explicitly setting source\_dest\_check to null or “” but neither work.

Any help would be great.

---

<div class="post-metadata">

**Author:** ![tbugfinder](https://sea2.discourse-cdn.com/hashicorp/user_avatar/discuss.hashicorp.com/tbugfinder/32/12689_2.png) [@tbugfinder](https://discuss.hashicorp.com/u/tbugfinder)\
**Post date:** [March 19, 2021, 10:26am UTC](https://discuss.hashicorp.com/t/for-each-null-value/22253/2 "2021-03-19T10:26:22Z")

</div>

Please reformat your code properly using triple backticks this helps reading and copy-pasting it for testing.

---

<div class="post-metadata">

**Author:** ![tbugfinder](https://sea2.discourse-cdn.com/hashicorp/user_avatar/discuss.hashicorp.com/tbugfinder/32/12689_2.png) [@tbugfinder](https://discuss.hashicorp.com/u/tbugfinder)\
**Post date:** [March 19, 2021, 10:28am UTC](https://discuss.hashicorp.com/t/for-each-null-value/22253/3 "2021-03-19T10:28:52Z")

</div>

> [@jprouten](#):
>
> resource “aws\_network\_interface” “mgmt\_eth” {
> 
> for\_each = var.ec2

Your `for_each` iterates on var.ec2 not evaluating subnet\_mgt. If that’s a condition then it has to be added.

---

<div class="post-metadata">

**Author:** ![apparentlymart](https://sea2.discourse-cdn.com/hashicorp/user_avatar/discuss.hashicorp.com/apparentlymart/32/702_2.png) [@apparentlymart](https://discuss.hashicorp.com/u/apparentlymart)\
**Post date:** [March 22, 2021, 7:06pm UTC](https://discuss.hashicorp.com/t/for-each-null-value/22253/4 "2021-03-22T19:06:08Z")

</div>

Hi @jprouten,

The main requirement for [`for_each`](https://www.terraform.io/docs/language/meta-arguments/for_each.html) is that you provide a map with one element per instance you want to declare. From that requirement it follows that in order to create _zero_ instances you’d need to provide a map with zero elements.

There are lots of ways to conditionally create a map with zero elements, but one concise way I like is to use a [`for` expression](https://www.terraform.io/docs/language/expressions/for.html) with an `if` clause that filters out some or all of the elements based on a condition.

In your case it sounds like you either want to include either all of the elements or none of them, and so that would involve an `if` expression which only refers to globals, and not to anything about the current element:

```auto
  for_each = {
    for k, v in var.ec2 : k => v
    if var.enable_ec2
  }

```

For the above to work you would need to have a variable called `enable_ec2` with`type = bool`. When that variable is `false`, `if` will find its expression returns `false` for every element and so the `for` expression will produce an empty map.

Although you don’t need it in this particular case, you might also find it interesting to know that you can use this `if` clause to filter out only _some_ of the elements of the map, by writing an `if` clause that includes references to `k` and/or `v` to return `true` only for elements that should be kept:

```auto
  for_each = {
    for k, v in var.ec2 : k => v
    if v.name != "forbidden"
  }

```

The above is a silly, unrealistic example of skipping just instances whose name is `"forbidden"`. I doubt anyone would need to do exactly that, but hopefully you can see from that how you might use this in other situations to use only a subset of the elements of a given map.

---

<div class="post-metadata">

**Author:** ![aogorodnikov](https://sea2.discourse-cdn.com/hashicorp/user_avatar/discuss.hashicorp.com/aogorodnikov/32/22409_2.png) [@aogorodnikov](https://discuss.hashicorp.com/u/aogorodnikov)\
**Post date:** [December 8, 2021, 10:04pm UTC](https://discuss.hashicorp.com/t/for-each-null-value/22253/5 "2021-12-08T22:04:36Z")

</div>

Thank you for useful examples. I done a lot of HCL code using your answers.
