Home > OS >  Creating multiple namespaces using Terraform
Creating multiple namespaces using Terraform

Time:09-24

I am trying to create multiple namespaces from a json blob input file like below:

my tfvars.json file

{
    "example1" : [
        {
            "namespace_name" : "test-1", 
            "team_name" : "test",  
        },
        {
            "namespace_name" : "test-2", 
            "team_name" : "test2", 
        }
   ]
}

My main.tf file looks as below:

resource "kubernetes_namespace" "aks_namespace" {
    metadata {
      annotations = {
        name = var.namespace_name
      }
      labels = {
        name = var.team_name
      }
      name = var.namespace_name
      }
}

I have tried almost all the options available like for_each and dynamic.. nothing seems to be working to create the namespaces in loop. Just wondering if this is really possible.. Unfortunately, I am not supposed to change the input .json format.. Any suggestions or ideas?

CodePudding user response:

I tried with all possibilities using your details but as the example1 is a tuple value , declaring it in for_each will error out creating namespace.

So , as a solution I declared variable example1 in terraform.tfvars.json as below:

{    "example1" : [
    [
            "test-1", 
            "test"
         ],
        [
         "test-2", 
        "test2" 
        ]
    ]
} 

This is the main.tf I am using:

terraform {
  required_providers {
    kubernetes = {
      source = "hashicorp/kubernetes"
      version = "2.5.0"
    }
  }
}
variable "example1" {
  
}

provider "kubernetes" {
  # Configuration options
}
resource "kubernetes_namespace" "aks_namespace" {
  for_each = {for i,v in var.example1: i=>v}
metadata {
  annotations = {
    name = each.value[0]
  }
  labels = {
    name = each.value[1]
  }
  name = each.value[0]
}
}

Outputs:

enter image description here


Update: terraform.tfvars.json

{
    "example1" : [
        {
            "namespace_name" : "test-1", 
            "team_name" : "test"
        },
        {
            "namespace_name" : "test-2", 
            "team_name" : "test2"
        }
   ]
}

main.tf

terraform {
  required_providers {
    kubernetes = {
      source = "hashicorp/kubernetes"
      version = "2.5.0"
    }
  }
}
variable "example1" {
  type = list(object({
    namespace_name = string
    team_name = string
  }))
}

provider "kubernetes" {
  # Configuration options
}
resource "kubernetes_namespace" "aks_namespace" {
  for_each = {for i,v in var.example1: i=>v}
metadata {
  annotations = {
    name = var.example1[each.key].namespace_name
  }
  labels = {
    name = var.example1[each.key].team_name
  }
  name = var.example1[each.key].namespace_name
}
}
  • Related