templatesterraformkubernetes-helm

Pass list of objects as argument in terraform helm_release


I have a variable list of objects tolerations, which I am trying to pass to helm_release terraform resource. The code block below is part of a module and I am importing that module in different place and using tolerations as an input.

locals {
  metabase_namespace   = "metabase-test"
}
    
resource "helm_release" "metabase-test" {
  name       = "metabase-test"
  namespace  = local.metabase_namespace
  repository = "https://pmint93.github.io/helm-charts"
  chart      = "metabase"
  version    = "2.14.4"
    
  values = [
    templatefile("${path.module}/templates/metabase-test.tpl", {
      tolerations = var.tolerations
    })
  ]
}
    
variable "tolerations" {
  type = list(object({
  key      = string
  operator = string
  value    = optional(string)
    effect   = optional(string)
  }))
  default = [{
    key      = "metabase"
    operator = "Equal"
    value    = "true"
    effect   = "NoSchedule"
  }]
}

and metabase-test.tpl

tolerations: ${tolerations}

I am trying to achieve this

tolerations:
  - key: metabase1
    operator: Equal
    value: "true"
    effect: NoSchedule
  - key: metabase2
    operator: Equal
    value: "true"
    effect: NoSchedule

I need to pass it through this specific variable given our setup, but cannot get it to render properly.


Solution

  • Marko E's answer is a simple and elegant solution.

    If you want to have more control regarding the indentation and generated quotes " you can change your metabase-test.tpl like this:

    tolerations:
    %{ for toleration in tolerations ~}
      - key: ${ toleration.key }
        operator: ${ toleration.operator }
        value: ${ toleration.value }
        effect: ${ toleration.effect }
    %{ endfor ~}
    

    Generated output:

    tolerations:
      - key: metabase1
        operator: Equal
        value: true
        effect: NoSchedule
      - key: metabase2
        operator: Equal
        value: true
        effect: NoSchedule
    
    

    Or, as an alternative:

    tolerations:
    %{ for toleration in tolerations ~}
      - key: ${ chomp(yamlencode(toleration.key)) }
        operator: ${ chomp(yamlencode(toleration.operator)) }
        value: ${ chomp(yamlencode(toleration.value)) }
        effect: ${ chomp(yamlencode(toleration.effect)) }
    %{ endfor ~}
    

    Generated output:

    tolerations:
      - key: "metabase1"
        operator: "Equal"
        value: "true"
        effect: "NoSchedule"
      - key: "metabase2"
        operator: "Equal"
        value: "true"
        effect: "NoSchedule"
    
    

    PS: chomp function removes the newline characters generated by yamlencode