Search code examples
terraformnginx-ingress

Terraform nginx ingress dynamic for_each rules host


Trying to create a dynamic host rules that I previously had in my ingress yaml file. Main difference TF doesn't have 'rules' they have a single 'rule', but I assume it's just a naming conversion. Currently im creating an ingress for each item, but I'd like to do a dynamic rule. I understand the dynamic has to be in a resource/data/etc. How would I accomplish this? (not a working example)

resource "kubernetes_ingress" "test" {

  wait_for_load_balancer = false
  metadata {
    name = "my-test-${each.value}"
    namespace = kubernetes_namespace.test.metadata.0.name
    annotations = {
      "kubernetes.io/ingress.class" = "nginx"
    }
  }

  spec {
    dynamic "rule" {
      for_each = toset(var.types)
      content {
        host = "${each.value}.test.mydomain.com"
        http {
          path {
            path = "/"
            backend {
              service_name = kubernetes_service.test[each.value].metadata.0.name
              service_port = 8080
            }
          }
        }
      }
    }
  }

}

Solution

  • When you are using dynamic blocks, you have to use, in your case, rule, not each to refer to items in your for_each:

    resource "kubernetes_ingress" "test" {
    
      #..
    
      spec {
        dynamic "rule" {
          for_each = toset(var.types)
          content {
            host = "${rule.value}.test.mydomain.com"
            http {
              path {
                path = "/"
                backend {
                  service_name = kubernetes_service.test[rule.value].metadata.0.name
                  service_port = 8080
                }
              }
            }
          }
        }
      }