其他分享
首页 > 其他分享> > 【解决了一个小问题】terraform创建service后,如何获取VIP的值?

【解决了一个小问题】terraform创建service后,如何获取VIP的值?

作者:互联网

创建一个pod后,再为这个pod创建一个对应的service,便于公开一个地址给外部访问。
有时候需要根据service的vip,再进行下一步的配置。
下面的代码演示如何获取service的vip:

# 最核心的配置
terraform {
  required_providers {
    kubernetes = {
      source  = "hashicorp/kubernetes"
      version = ">= 2.0.0"
    }
  }

  backend "local" {

  }
}

# TKE群集的IP和KEY
provider "kubernetes" {
  config_path = "../tencentyun-cls-xxxx-config.yaml"
}

# 这里省略创建容器的代码

# 创建POD对应的service
resource "kubernetes_service" "vm-storage-service" {
  metadata {
    name      = "vm-storage-services"
    namespace = "default"
    labels    = {
          "k8s-app"                    = "vm-storage"
          "qcloud-app"                 = "vm-storage"
        }
    annotations = {
      "description"                                                 = "headless service for vm-storage"
      "service.kubernetes.io/qcloud-loadbalancer-clusterid"         = "cls-xxxxxx"
      "service.kubernetes.io/qcloud-loadbalancer-internal-subnetid" = "subnet-xxxxxx"
    }
  }

  spec {
    port {
      name        = "8482-80-tcp"
      port        = "80"
      protocol    = "TCP"
      target_port = "8482"
    }
    selector                = {
          "k8s-app"                    = "vm-storage"   # 这里是绑定的POD
          "qcloud-app"                 = "vm-storage"
        }
    session_affinity        = "None"
    type                    = "LoadBalancer"
    external_traffic_policy = "Cluster"
  }
}

# 可以在执行完成后输出VIP
output "load_balancer_ip" {
  value = "${kubernetes_service.vm-storage-service.status.0.load_balancer.0.ingress.0.ip}"  # vm-storage-service 是上面创建的 service 的名字
}

# config-map的建立方法
# 可以把vip写入配置
resource "kubernetes_config_map" "ahfu-vm-storage-vip" {
  metadata {
    name      = "ahfu-vm-storage-vip"
    namespace = "default"
  }
  data = {
      "my.yaml" = "${kubernetes_service.vm-storage-service.status.0.load_balancer.0.ingress.0.ip}"
  }
}

P.S 能够直接引用output的值呢?代码中死活做不到(只有父module引用子module的情况),希望有研究明白的小伙伴给个例子。
Have fun!

标签:service,kubernetes,vip,storage,vm,qcloud,terraform,VIP
来源: https://www.cnblogs.com/ahfuzhang/p/16386339.html