Search code examples
amazon-web-servicesazureterraformdevopsterraform-provider-azure

Terraform assign variable value using for loop if condition is true


I need to assign short_id to variable short_location_name,

I have map short_location_names in below terrfaorm code, if "var.location" is "westus", I need to assign short_location_names "wus"

my_code:

locals {
  short_location_names = {
      "westus": "wus",
      "eastus": "eus",
      "westus2": "wus2",
      "eastus2": "eus2"
  }
  short_location_name = {
    for location, short_id in local.short_location_names: location == var.location ? short_location_name => short_id
  }

I tried above code, I getting error missing false statement, How to fix?


Solution

  • Use the lookup function instead:

    short_location_name = lookup(local.short_location_names, var.location, null)
    

    or

    short_location_name = { var.location: lookup(local.short_location_names, var.location, null) }
    

    Or simply local.short_location_names[var.location] if the value will always be present in the map.