Ask Your Question
2

How to perform iteration in the Terraform provider for Kubernetes?

asked 2023-07-21 12:16:03 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-21 12:41:02 +0000

scrum gravatar image

To perform iteration in the Terraform provider for Kubernetes, you can use the count meta-argument or the for_each meta-argument.

  • count meta-argument: This meta-argument allows you to create multiple instances of a resource or module by specifying an integer value. For example, if you want to create 3 replicas of a Kubernetes deployment, you can use the count meta-argument like this:
resource "kubernetes_deployment" "example" {
  metadata {
    name = "example"
  }

  spec {
    replicas = 3
    template {
      spec {
        container {
          image = "nginx:latest"
          name  = "nginx"
          port {
            container_port = 80
          }
        }
      }
    }
  }
}
  • for_each meta-argument: This meta-argument allows you to create multiple instances of a resource or module by specifying a map or a set of values. This is useful when you want to create multiple instances of a resource with different configurations. For example, if you want to create multiple Kubernetes namespaces with different labels, you can use the for_each meta-argument like this:
variable "namespaces" {
  type = map(object({
    labels = map(string)
  }))
  default = {
    dev = {
      labels = {
        environment = "development"
      }
    }
    prod = {
      labels = {
        environment = "production"
      }
    }
  }
}

resource "kubernetes_namespace" "example" {
  for_each = var.namespaces

  metadata {
    name = each.key
    labels = each.value.labels
  }
}

In the above example, we are iterating over a map variable called namespaces and creating two Kubernetes namespaces with different labels using the for_each meta-argument. The each.key and each.value variables refer to the key and value of the current iteration.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-21 12:16:03 +0000

Seen: 19 times

Last updated: Jul 21 '23