Search code examples
terraformterragrunt

Pass list of environment variables to resource


i'm trying to pass a list from my terragrunt.hcl inputs, with environment variables for a container. But i can't get it to work.

terragrunt.hcl:

inputs = {
    containers_env = {
        "ENV_TEST" = "testing"
        "ENV_TEST_2" = "testing2"
    }
}

main.tf:

resource "kubernetes_cron_job" "cronjob" {
    metadata {
        name      = var.metadata_name
        namespace = var.metadata_namespace
    }
    spec {
        schedule                      = var.spec_schedule
        concurrency_policy            = var.spec_concurrencyPolicy
        failed_jobs_history_limit     = var.spec_failedJobsHistoryLimit
        successful_jobs_history_limit = var.spec_successfulJobsHistoryLimit
        job_template {
            metadata {}
            spec {
                template {
                    metadata {}
                    spec {
                        restart_policy                      = var.template_spec_restartPolicy
                        termination_grace_period_seconds    = var.template_spec_terminationGracePeriodSeconds
                        container {
                            name                = var.containers_name
                            image               = var.containers_image
                            image_pull_policy   = var.containers_imagePullPolicy
                            command             = var.containers_command
                            env                 = var.containers_env
                        }
                    }
                }
            }
        }
    }
}

variables.tf:

variable "containers_env" {
    description = ""
    type        = map(string)
}

I'm getting the error:

Error: Unsupported argument

  on main.tf line 41, in resource "kubernetes_cron_job" "cronjob":
  41:                                                   env                             = var.containers_env

An argument named "env" is not expected here. Did you mean to define a block
of type "env"?

Terraform: v0.12.13 Terragrunt: v0.21.5


Solution

  • The container block type seems to require environment variables to be defined as a sequence of nested env blocks. Written out manually, they might look something like this:

    env {
      name  = "ENV_TEST"
      value = "testing"
    }
    env {
      name  = "ENV_TEST_2"
      value = "testing2"
    }
    

    To produce these blocks dynamically based on var.containers_env, we can use a dynamic block, with var.containers_env as its repetition expression:

    dynamic "env" {
      for_each = var.containers_env
      content {
        name  = env.key
        value = env.value
      }
    }