So on our last post we used for_each with terraform 0.12.6+ to create multiple resources with a single reference based on a list.

In this post we will se how we may conditionally create resources using for_each as well. Sounds strange, but its what happens without syntatic sugar for conditionals in Terraform :D

If you used conditional in Terraform before, you may have noticed multiple uses of count for creating resources.

Usual example, and considering our previous example for ecr repository would be like this:

resource "aws_ecr_repository" "default" {
  count = var.create_repository ? 1 : 0
  name  = "nginx"
}

So, in the above example we used count, along with the elvis operator for validating the boolean value of a var named create_repository, ending up, in one copy or zero copies of the resource.

Count is actually the error-prone predecessor for the resources list creation. It would create multiple copies of the same resource, the same way as for_each, except that it references the created resources in state by index number. Meaning, that if you would change a variable, it would end up messing things.

So but, how may we actually use for_each to achieve the same goal?

Example

variable "images" {
    type = list(string)
    default = []
}

locals{
    images = { for v in var.images : v => v }
}

resource "aws_ecr_repository" "default" {
  for_each = local.images
  name  = "${each.key}"

It’s almost the same logic. This time we just end up passing an empty map, that would result in resources not being created.

And that’s it. Thank you for reading.

André Ilhicas dos Santos

Devops Padawan, curious about systems automation, learning new languages, paradigms tools each day.

ilhicas ilhicas


Published