Terraform 部署条件

Terraform Condition on Deployment

我在部署中使用 Terraform。 我有一个部署列表并在部署时使用 for_each。根据字符串条件,我需要添加一个 sidecar。

简而言之,我需要写一个添加sidecar图像的条件。

类似的东西:

${substr(each.key, 0, 3) == "tst" ? 1 : 0 }

有办法实现吗?

这是我的部署 tf:

resource "kubernetes_deployment" "x" {
  for_each = data
  metadata {
    name = each.key
    labels = {
      app = each.key
      name = each.key
    }
    namespace = var.namespace
  }
  spec {
    replicas = 1

    selector {
      match_labels = {
        app = each.key
      }
    }
    template {
      metadata {
        labels = {
          app = each.key
          name = each.key
        }
      }
      spec {
        service_account_name = "default"

        container {
          image = each.value
          image_pull_policy = "Always"
          name = each.key
        }
        // I need a condtion to create the second container
        container {
          image = "sidecar_image"
          image_pull_policy = "Always"
          name = "sidecar-container"
          port {
            name           = "default-port"
            container_port = 50050
          }
        }

        restart_policy = "Always"
      }
    }
  }
}

您可以对第二个 container 块使用 dynamic 块,以使其成为有条件的。例如,考虑以下代码:

dynamic "container" {
    for_each          = var.is_test ? [1] : []
    image             = "sidecar_image"
    image_pull_policy = "Always"
    name              = "sidecar-container"
    port {
        name           = "default-port"
        container_port = 50050
    }
}

请注意,该条件需要更多关注,但我认为这应该足以让您入门。

一般来说,您可以看到条件嵌套块的细微差别 。不过,要根据您的具体情况进行调整:

dynamic "container" {
  for_each = range(substr(each.key, 0, 3) == "tst" ? 1 : 0)
 
  content {
    image = "sidecar_image"
    image_pull_policy = "Always"
    name = "sidecar-container"
    port {
      name           = "default-port"
      container_port = 50050
    }
  }
}

这假设您的 for_each 元参数值中的 data 键是您问题中提供的资源的格式正确的

我注意到关于你的条件的一个直接问题是从索引 0 到 3 的子字符串将包含四个值,而你正在测试一个包含三个字符的字符串。你可能想做:

substr(each.key, 0, 2)

或者也许还有:

can(regex("^tst", each.key))

但无论哪种方式,您提供的条件总是 return false.