Terraform variable default value with condition

I have an app settings configuration that needs to be done for more than 90 app services, these settings are basically adding keys for integration with azure app insights.

For creating and configuring app services, we have a built-in module.

For the app settings part we currently have this through an env with map values:

variable “app_settings” {
description = “A key-value pair of App Settings.”
type = map(string)
default = {}
}

And in the directory of each webapp I only specify the settings I need:

app_settings = {
“SPRING_PROFILES_ACTIVE” = “dev”
}

I would like to put these settings in the default of my variable, but my question is if I can make conditions, for example:

If the environment is dev: take the following block:

variable “app_settings” {
description = “A key-value pair of App Settings.”
type = map(string)
default = {
“SPRING_PROFILES_ACTIVE” = “dev”
}
}

If it’s hml get the following block:

variable “app_settings” {
description = “A key-value pair of App Settings.”
type = map(string)
default = {
“SPRING_PROFILES_ACTIVE” = “hml”
}
}

I would like to do this at the module level so as not to configure more than 90 webapps with such a simple configuration.

Hi @rodrigoaraujo1,

A default value is always a static value to use when the variable isn’t set by the module caller. Therefore it cannot vary automatically based on anything else.

The design you were previously using to set the value from outside the module was already the most straightforward way to achieve the result you described.

An alternative is to move the definition of the app settings map to be a local value inside the module and change the input variables to instead be the higher-level data needed to populate it:

variable "environment" {
  type = string
}

locals {
  app_settings = tomap({
    SPRING_PROFILES_ACTIVE = var.environment
  })
}

This approach changes the level of abstraction so that the “app settings” are an implementation detail of the module. Instead of defining the app settings map directly, the user of the module defines individual values that the app settings will be derived from. I only showed the one setting you included in your question here, but if course you can define more variables and produce a more elaborate app_settings value if you need to.

1 Like