Search code examples
terraformterraform-provider-azure

How to retrieve the value from a map-type variable using the key?


Here is my code:

variable "project_name" {
  type        = map
  description = "Name of the project."
  default     = {
    dr       = "dr"
    prelive  = "prelive"
    prod     = "prod"
  }
}
   
variable "env" {
  description = "env: dr, prelive or prod"
}

variable "client_id" {
  type        = map
  sensitive   = true
  default     = {
    dr      = "dr-client-id"
    prelive = "prelive-client-id"
    prod    = "prod-client-id"
  }
}

variable "client_secret" {
  type        = map
  sensitive   = true
  default     = {
    dr      = "dr-client-secret"
    prelive = "prelive-client-secret"
    prod    = "prod-client-secret"
  }
}

    resource "azurerm_kubernetes_cluster" "cluster" {
      ....
        service_principal {
          client_id     = ...
          client_secret = ...
      }
}

I'm running this with one of these commands:

terraform apply -var 'env=dr' 
terraform apply -var 'env=prelive' 
terraform apply -var 'env=prod'

When I pass, for example, env=dr, I want to get the values from the dr variable, and set those on service_principal.

I need to have something like the following:

For env=dr:

service_principal {
  client_id     = dr-client-id
  client_secret = dr-client-secret
}

For env=prod:

service_principal {
  client_id     = prod-client-id
  client_secret = prod-client-secret
}

Solution

  • Your var.client_id and var.client_secret are maps. This means that you can refer to them as follows:

    var.client_id[key] # where key is var.env
    var.client_secret[key]
    

    This means that your resource could be:

        resource "azurerm_kubernetes_cluster" "cluster" {
          ....
            service_principal {
            client_id     = var.client_id[var.env]
            client_secret = var.client_secret[var.env]
          }
    }
    

    You can also use lookup, if you want to provide some default value.