Terraform Condition on Deployment

Viewed 157

I'm using terraform in deployment. I have a list of deployment and using for_each on deployment. Based on string condition I need to add a sidecar.

Briefly, I need to write a condition to add a sidecar image.

Something like it:

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

Is there a way to achieve that?

Here is my deployment 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"
      }
    }
  }
}
2 Answers

You could use a dynamic block for the second container block in order to make it conditional. For example, consider the following piece of code:

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
    }
}

Note that the condition will require some more attention but I think this should be enough to get you started.

In general you can see the nuances around conditional nested blocks in this answer. To tailor this to your specific situation though:

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
    }
  }
}

This assumes well-formed data keys in your for_each meta-argument value for the resource as provided in your question.

One immediate issue I note with your conditional is that the substring from index 0 to 3 will contain four values, and you are testing against a string with three characters. You probably wanted to do:

substr(each.key, 0, 2)

or perhaps also:

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

but either way your provided conditional will always return false.

Related