Search code examples
terraformamazon-eks

How to (elegantly) create a dynamic map inside a variable?


I have a list(string) as a declared variable, and need to create a map out of it inside a module variable. The context is the AWS eks module, which contains an input named eks_managed_node_groups of type any, although internally is is actually a map:

  eks_managed_node_groups = {
    node_group_name = {
      name = name
      ...
    }
  }

Want I want to achieve is to have a declared variable of type list(string), in my case containing availability zone identifier, e.g. [ "a", "b", "c" ]. Out of this, I want to generate a map that contains one entry per value in the variable, so I get three map elements in eks_managed_node_groups, like this:

  eks_managed_node_groups = {
    node_group_a = {
      name = a
      ...
    }
    node_group_b = {
      name = b
      ...
    }
    node_group_c = {
      name = c
      ...
    }
  }

I got this working, but the solution is not really readable:

eks_managed_node_groups = zipmap(
    [ for az in var.availability_zones : "nodes_${az}" ],
    [ for az in var.availability_zones : {
      name = "${az}",
      ...
    }]
  )

and I would expect there should be a much more elegant way to achieve this.


Solution

  • You could remove the zipmap function and simply assign the nodes_${az} as the key in a single for expression within the map constructor. Otherwise this type of substantial data transformation does require the code you utilize in the question:

    eks_managed_node_groups = {
      for az in var.availability_zones : "nodes_${az}" => {
        name = $az,
        ...
      }
    }