Select values based on another va value (like an if, but with more than 2 choices)

I am struggling with a problem. I’m trying to deploy an app_service, but the “app_settings” section should be different based on a key(The app_setting value is different if we are in “lab”, “dev” or “prod”

It should be easy with an If, but that doesn’t exist in terraform. I tried with a conditional expression, but it doesn’t work because it’s a true or false.(or maybe it could work, but my tries were met with failure so far)

Any ideas how I could deal with this case?

Hi @kinwolfqc,

A common way to do things like this in Terraform is to use a map as a lookup table to select a value based on a particular key. I’m not very familiar with the “app service” concept you’re referring to here, but I can show a general example of what that might look like and hopefully you can adapt it to the specific services you are working with:

variable "environment" {
  type = string
}

locals {
  env_app_settings = {
    lab = {
      something = "foo"
    }
    dev = {
      something = "bar"
    }
    prod = {
      something = "baz"
    }
  }
}

To access the appropriate something value depending on the var.environment variable, you can write an expression like this:

local.env_app_settings[var.environment].something
1 Like

Thanks for the quick reply

Aaahh, the dreaded map… but yes, I think this would solve my problem. I guess it’s time I stop avoiding the map! I’ll tackle this next Monday and report back.

Thanks!

Feedback from the proposed solution: It worked beautifully!

I admit I stayed away from map because dealing with for_each and for is really intimidating in terraform, and while I found out how to write the correct for_each syntax for this one, every time I look back at it(see below), I have to redo the research because it’s really non intuitive.

  for_each = {
    for v in var.appServList : v => v if v == "prod"
  }

So,solved, thanks! :slight_smile: