Terraform For each Conditional check

Team,

I have a input json which is having some environmental details in the form of map.

"env" : {

     

      "dev":{

        "backendAppId" : "XXXXXXXXXXXXXXXXXXXXX",

        "backendServiceUrl" :"https://dev-url",

        "roleName" :"Dev.Access"

      },

       "dit":{

        "backendAppId" : "YYYYYYYY",

        "backendServiceUrl" :"https://dit-url",

        "roleName" :"Dit.Access"  

      }
}

For each environment , we have a key and it corresponding values.

We are using Infrastructure as a code for the Azure api manager and replacing this values at run time in the policy file.

My question is if we are deploying in Dev we need to get the Dev env information and use it.

Below is the data template we are using , based on the env input we need to pick the right value.

data "template_file" "api_policy_file" {

   template = file(each.value.policyFile)

   vars = {

       tenant_id = var.tenant_id

 for {
      **backend_app_id =  env.get(dev).backendAppId**
   
}
       

   }

}

Can you please help me how to iterate through map and get the value based on the condition .

locals {

  api_details = jsondecode(file("api-source.json"))

  envInfo =  [for env in api_details.env: env["dev"]]  

}


data "template_file" "api_policy_file" {

   template =  var.policyFile

   vars = {

     tenant_id = var.tenant_id

     role-name = locals.envInfo.roleName

     backend-app-id= locals.envInfo.backendAppId

     backend-service-url =locals.envInfo.backendServiceUrl

  }

}

is it a right way to get the dev env info?

Hi @bsudabathula,

Iā€™m not sure I fully understand what you want to do, but I think the following will do what you describe:

variable "environment" {
  type = string
}

variable "tenant_id" {
  type = string
}

locals {
  api_details     = jsondecode(file("api-source.json"))
  env_api_details = local.api_details[var.environment]
}

data "template_file" "api_policy_file" {
  template =  var.policyFile
  vars = {
    tenant_id           = var.tenant_id
    role_name           = locals.env_api_details.roleName
    backend_app_id      = locals.env_api_details.backendAppId
    backend_service_url = locals.env_api_details.backendServiceUrl
  }
}

The main important part of this is local.api_details[var.environment], which looks up a single element of local.api_details whose key matches the string given in var.environment.

1 Like