Terraform: create namespaces and role binding using lists

11/6/2020

The namespace is created in next way, so "role bindings" are applied depending of the "app_env" code

**variables.tf**
variable app_name {}
variable app_env {}

locals {
  custom_role_dev = "Enterprise Development Project"
  custom_role_prd = "Enterprise Production Project"
} 

**main.tf**
resource "kubernetes_namespace" "kube_ns" {
  metadata {
    name = var.app_name
  }
}

resource "kubernetes_role" "custom_role_dev" {
  count var.app_env == "d" ? 1 : 0
  metadata {
    name      = local.custom_role_dev
    namespace = var.app_name
  }
  rule {
    api_groups = [""]
    resources  = ["<options>"]
    verbs      = ["*"]
  }
  depends_on = [kubernetes_namespace.kube_ns]
}

resource "kubernetes_role" "custom_role_prd" {
  count var.app_env == "p" ? 1 : 0
  metadata {
    name      = local.custom_role_prd
    namespace = var.app_name
  }
  rule {
    api_groups = [""]
    resources  = ["<options>"]
    verbs      = ["*"]
  }
  depends_on = [kubernetes_namespace.kube_ns]
}

In order to create several namespace and applying their respective roles, I want to use "lists" to replace "app_name" variable but I don't know how to iterate the "kubernetes_role" block.

I think this 2 links are very close what I want to do

https://stackoverflow.com/questions/63409307/convert-list-to-map-with-index-in-terraform

https://stackoverflow.com/questions/48301709/terraform-conditionally-creating-a-resource-within-a-loop

Can this be done with "for_each" or "count"?

-- cgratelli
azure
azure-aks
kubernetes
terraform

0 Answers