Terraform for_each over tuples

If you have been recently working on Terraform for_each one of the things you might across is how to iterate over tuples with a for_each.

The secret lies in using for in combination with for_each. Line number 16

locals {
  ssm = [
      name  = "/ZEUS/PROD/HEALTH"
      data = "Age"
      name  = "/ZEUS/PROD/GROUP"
      data = "Red"
resource "aws_ssm_parameter" "params" {
  for_each = {
    for cj in local.ssm : cj.name => cj
  name      = each.key
  type      = "String"
  value     = each.value.data
  overwrite = true

so how does it work?

The for instead the for_each returns the single element from the map to the for_each.
cj.name will be assigned the resource unique identifier.

Make sure that the resource index for example here: name is something that remains constant! Otherwise, the resource will be deleted

In the previous versions of Terraform, we could achieve a similar goal, by using count however this is extremely risky!

If you change the position of an item in a list, the resource will be deleted. This won’t be happening anymore by using for_each. This is because the resource unique identifier can be set to a name.

for_each has changed the way we write code in Terraform. It is now more close to a programming language and this gives us more flexibilty. Previously we had to use count which was error prone and not a clean way. For example: creating a subnet in Vnet in AzureĀ  using a list variable and for_each makes the code easier to read and customizable!