Terraform 遍历自定义变量对象

Terraform looping over custom variables object

我想做什么?

我想使用 terraform 创建一个 kubernetes service 对象,但要使其可重复使用。所以每次有新服务时,我都可以附加变量。

我的问题:

我一直在阅读和尝试不同的东西,但我不确定如何遍历具有多个键值对的“注释”和“选择器”。

代码示例

Variables.tf 我想使用它构建实际的 terraform 资源。

variable "apps" {
  default = {
    "app1" = {
      svc_name  = "app1"
      namespace = "testns"
      annotations = {
        "testannotation" = "ann1"
      }
      selector = {
        app = "podinfo"
        env = "dev"
      }
      ports = {
        name       = "http"
        port       = 80
        protocol   = "TCP"
        targetPort = 8008
      }
    },
    "app2" = {
      svc_name  = "app2"
      namespace = "testns"
      annotations = {
        "testannotation" = "ann1"
      }
      selector = {
        app = "someapp"
        env = "qa"
      }
      ports = {
        name       = "http"
        port       = 8080
        protocol   = "TCP"
        targetPort = 8080
      }
    },
  }
}

这里是 main.tf,我想在其中循环变量的“注释”和“选择器”,因为它们可能不止一个。但是只有一个“注释”和“选择器”块。所以我不能使用“动态”,因为它会生成许多这样的块。

resource "kubernetes_service" "service" {
  for_each = var.apps
  metadata {
    name      = each.value.svc_name
    namespace = each.value.namespace
    # annotations = {
    #   HOW DO I GET THE ANNOTATIONS HERE
    # }
  }
  spec {
    selector = {
      ## HOW DO I GET THE SELECTORS FROM VARIABLEES HERE
    }
    session_affinity = "ClientIP"
    port {
      port        = each.value.ports.port
      target_port = each.value.ports.targetPort
    }

    type = "ClusterIP"
  }
}

如有任何指南、链接或建议,我将不胜感激!

您对其他属性执行相同的操作:

resource "kubernetes_service" "service" {
  for_each = var.apps
  metadata {
    name      = each.value.svc_name
    namespace = each.value.namespace
    annotations = each.value.annotations 
  }
  spec {
    selector = each.value.selector 
    session_affinity = "ClientIP"
    port {
      port        = each.value.ports.port
      target_port = each.value.ports.targetPort
    }

    type = "ClusterIP"
  }
}