Mixing loops and module outputs

Hi everyone,

I’m trying to render ‘N’ kubernetes secrets. We use a legacy module called my_certificates defining two outputs: certs and keys

I tried to use a for_each loop but I’m in trouble interpolating each.key in the output:

suppose the following domains

domains = ["example1-com","example2-com"]

This obviously fails:

module.my_certificates.certs.${each.key}

And this renders a string (not valid as it does not render content):

"module.my_certificates.certs.${each.key}"

What I’m trying to get with this loop:

module.my_certificates.certs.example1-com
module.my_certificates.keys.example1-com
module.my_certificates.certs.example2-com
module.my_certificates.keys.example2-com

Here’s my code:

resource "kubernetes_secret" "certificates" {
  for_each = toset(var.domains)
  metadata {
    name      = each.key
  }

  data = {
    "tls.crt" = module.my_certificates.certs.${each.key}
    "tls.key" = module.my_certificates.keys.${each.key}
  }

  type = "kubernetes.io/tls"
}

Thanks in advance,

Hi @lpzdvd-packlink!

If your certs and keys outputs are both maps – which seems to be the case based on what you tried so far – you can use the index syntax to look up an element dynamically, rather than statically as with the attribute syntax:

  data = {
    "tls.crt" = module.my_certificates.certs[each.key]
    "tls.key" = module.my_certificates.keys[each.key]
  }
1 Like

Works like a charm.
I am ashamed of having asked something so simple.

Thank you so much !

1 Like