1 | initial version |
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.