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?

  1. The for instead the for_each returns the single element from the map to the for_each. 
  2. 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.