Search code examples
terraform

If key does not exist in map, use default value


I have a locals variable defined as so:

locals {
  subnets = {
    # AWS Account:
    "222222222222" = {
      # Environment name:
      "prod" = {
        "us-west-2" : ["subnet-11111111111", "subnet-22222222", "subnet-3333333", "subnet-333333"]
      }
      "default" = {
        "us-east-2" : split(",", data.terraform_remote_state.vpc.outputs.private_subnets)
      }
    }
  }
}

# and I can reference it like so:
subnet_ids = local.subnets[var.aws_account_id][var.environment][var.region]

Unfortunately, the only two possible keys for var.enviroment are "prod" or "default".

What I really want to do is: (pseudo code):

if var.environment is not a key in local.subnets[var.aws_account_id], then use the "default" value for var.environment.

Is this possible in terraform?


Solution

  • The following example should be easy enough to understand and solve your issue.

    Sample code:

    variable "aws_account_id" {
      type        = string
      description = "AWS account ID."
      default     = "222222222222"
    }
    
    variable "environment" {
      type        = string
      description = "Environment name."
    }
    
    variable "region" {
      type        = string
      description = "AWS region."
      default     = "us-west-2"
    }
    
    locals {
      subnets = {
        # AWS Account:
        "222222222222" = {
          # Environment name:
          "prod" = {
            "us-west-2" : ["subnet-11111111111", "subnet-22222222", "subnet-3333333", "subnet-333333"]
          }
          "default" = {
            "us-east-2" : ["subnet-default-1", "subnet-default-2"]
          }
        }
      }
    
      selected_account     = local.subnets[var.aws_account_id]
      selected_environment = can(local.selected_account[var.environment]) ? var.environment : "default"
      selected_subnets     = local.selected_account[local.selected_environment]
    }
    
    output "selected_environment" {
      value       = local.selected_environment
      description = "Selected environment."
    }
    
    output "selected_subnets" {
      value       = local.selected_subnets
      description = "Selected subnets."
    }
    

    Running terraform plan -var environment=qa (non-existing environment):

    Changes to Outputs:
      + selected_environment = "default"
      + selected_subnets     = {
          + us-east-2 = [
              + "subnet-default-1",
              + "subnet-default-2",
            ]
        }
    

    Running terraform plan -var environment=prod (existing environment):

    Changes to Outputs:
      + selected_environment = "prod"
      + selected_subnets     = {
          + us-west-2 = [
              + "subnet-11111111111",
              + "subnet-22222222",
              + "subnet-3333333",
              + "subnet-333333",
            ]
        }