0

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

Convert list to map with index in Terraform

Terraform - conditionally creating a resource within a loop

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

cgratelli
  • 75
  • 1
  • 11
  • Not sure if that's possible, but would this be a solution for you? You can create reusable modules (preventing code duplicating) which allows you to use a template for the lines that are similar and only provide environment-specific parametes. https://www.nearform.com/blog/writing-reusable-terraform-modules/ – Casper Dijkstra Nov 08 '20 at 13:50
  • What is the list you want to use? I only see one value for the variable, where is the list? – Charles Xu Nov 09 '20 at 02:49

0 Answers0