Looping Over a Map Inside of a Resource

We’re in the process of using Terraform to setup a handful of Kubernetes deployments in our Google Kubernetes Engine. These are primarily legacy systems and, thus, have some legacy problems.

One of the problems we’re constantly running into is the amount of environment variables we’re having to set. I’d like to be able to loop over a map and set those environment variables instead of having to add an env block for each individual. I’m afraid that having that much copy pasta makes for very brittle code which there’s not a lot of tolerance for when working with infrastructure.

This is how we’re currently doing it:

resource "kubernetes_deployment" "deployment" {
  [...]
  spec {
    [...]
      spec {
        [...]
          env {
            name  = "ENV1"
            value = "some value"
          }
          env {
            name  = "ENV2"
            value = "another value"
          }
          env {
            name  = "ENV3"
            value = "more values"
          }
          [...]
      }
    }
    [...]
  }
}

In some cases, we’re adding 10+ env blocks.

What I think would be better is to use something like this:

variable "environment_variables" {
  type = map(any)
  default = {
    ENV1                             = "some value"
    ENV2                             = "another value"
    ENV3                             = "more values"
    [...]
  }
}

resource "kubernetes_deployment" "deployment" {
  [...]
  spec {
    [...]
      spec {
        [...]
          for_each = var.environment_variables {
            env {
              name  = each.key
              value  = each.value
            }
          }
          [...]
      }
    }
    [...]
  }
}

This would allow us to extend the variable and have the apply automatically add new blocks. However, I can’t seem to find a way to do this.

Am I missing something?

In any situation where you want to dynamically generate HCL blocks within Terraform, you need to look to this part of the documentation: https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks