Dagm Fekadu
Dagm Fekadu

Reputation: 610

Create dynamic block in kubernetes container block using terraform

I want to create a dynamic block that will able to dynamically create envs for docker container inside kubernetes using terraform.

I already tried creating a var of list and iterate over the envs but I am getting syntax error

Error: Reference to "count" in non-counted context

on kubernetes/kubernetes.main.tf line 68, in resource "kubernetes_deployment" "kube_deployment":

This is due to usage of count out of resource block.

I am looking now to create multiple envs like this

...

      env {
            name = "NAME"
            value = "VALUE"
          }
      env {
        name = "NAME"
        value = "VALUE"
      }
    .
    .
    .

is there anyway to create this iteration or any hacks to create dynamic envs in container block. I understand that dynamic blocks are only inside resource, data, provider, and provisioner. I was previously using helm to do this kind of templating but now I want to fully move to terraform. I would love any directions to solve such issue.

Thanks


resource "kubernetes_deployment" "kube_deployment" {
  metadata {
    name = var.deployment_name
    labels = {
      App = var.deployment_name
    }
  }

  spec {
    replicas = 1
    selector {
      match_labels = {
        App = var.deployment_name
      }
    }
    template {
      metadata {
        labels = {
          App = var.deployment_name
        }
      }
      spec {
        container {
          image = var.container_image
          name = var.container_name

          env {
            name = "NAME"
            value = "VALUE"
          }

          port {
            container_port = var.container_port
          }
        }
      }
    }
  }
}

Upvotes: 0

Views: 1467

Answers (1)

Dagm Fekadu
Dagm Fekadu

Reputation: 610

It was actually possible even if inside nested block of type resource, data, provider, and provisione..

here is a working code

resource "kubernetes_deployment" "kube_deployment" {
  metadata {
    name = var.deployment_name
    labels = {
      App = var.deployment_name
    }
  }

  spec {
    replicas = 1
    selector {
      match_labels = {
        App = var.deployment_name
      }
    }
    template {
      metadata {
        labels = {
          App = var.deployment_name
        }
      }
      spec {
        container {
          image = var.container_image
          name = var.container_name
          dynamic "env" {
            for_each = var.envs
            content {
              name = env.value.name
              value = env.value.value
            }
          }
          port {
            container_port = var.container_port
          }
        }
      }
    }
  }
}

Upvotes: 1

Related Questions