【分享代码片段】terraform中,如何从刚刚创建的 deployment 中获得所有容器的名字和 ip

作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢!


不好意思,刚刚才开始用 terraform,或许是更好的办法而我不知道。
知道的朋友请一定教教我。

下面是我的办法:

provider "kubernetes" {
  config_path = "../k8s.yaml"
}

resource "kubernetes_deployment" "ahfu-test-deploy-1" {
  metadata {
    namespace = "test-devops"
    name      = "ahfu-test-deploy-1"
    labels = {
      test = "ahfu-test-deploy-1"   # 这个标签用于过滤出 pod
    }
  }

  spec {
    replicas = 2

    selector {
      match_labels = {
        test = "ahfu-test-deploy-1"
      }
    }

    template {
      metadata {
        labels = {
          test = "ahfu-test-deploy-1"
        }
      }

      spec {
        container {
          image             = "alpine:3.18.4"
          image_pull_policy = "IfNotPresent"
          command           = ["/bin/sh"]
          args = [
            "/data/run.sh",
          ]

          name = "ahfu-test-deploy-1"

          resources {
            limits = {
              cpu    = "0.5"
              memory = "512Mi"
            }
            requests = {
              cpu    = "250m"
              memory = "50Mi"
            }
          }

          volume_mount {
            name       = "config-volume"
            mount_path = "/data/"
          }

          env {
            name = "CONTAINER_NAME"
            value_from {
              field_ref {
                field_path = "metadata.name"
              }
            }
          }

          env {
            name = "CONTAINER_IP"
            value_from {
              field_ref {
                field_path = "status.podIP"
              }
            }
          }

        volume {
          name = "config-volume"
          config_map {
            name = "ahfu-configmap-1"   # 这里准备了一个  configMap,内容是一个  bash 文件
          }
        }

      }
    }
  }
}

data "external" "filtered_pods" {
  depends_on = [kubernetes_deployment.ahfu-test-deploy-1]   # 等待前面的  deployment 创建成功
  # 用一条命令来得到 k8s 上的 pod 的数据
  # kubectl get pods -l test=ahfu-test-deploy-1 -n sige-test-devops -o json | jq -c  '{"r":  .|tojson }'
  # 猜测 terraform 中使用 golang 的  map[string]string 来反序列化 json,所以 key-value 必须都是 string 类型
  program = ["bash", "-c", "kubectl get pods -l test=ahfu-test-deploy-1 -n sige-test-devops -o json | jq -c '{\"r\": .|tojson }'"]
}

output "containers" {
   # 使用 json decode 来获取 kubectl 返回的内容
  value = [for item in jsondecode(data.external.filtered_pods.result.r).items : { container_name = item.metadata.name, container_ip = item.status.podIP }]
}

执行 terraform apply -auto-approve后,输出如下内容:

containers = [
  {
    "container_ip" = "10.42.0.175"
    "container_name" = "ahfu-test-deploy-1-846cf445f7-npbp2"
  },
  {
    "container_ip" = "10.42.1.96"
    "container_name" = "ahfu-test-deploy-1-846cf445f7-m5kqr"
  },
]

热门相关:睡服BOSS:老公,躺下!   墨先生,乖乖娶我   婚期一年   豪门隐婚:老婆别闹了   宝贝轻轻:总裁的独家宠爱