Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform 3 conditionals

Is it possible to have terraform decide between 3 statements? Like an if, else, else?

I want to run something similar to the following:

<CONDITION> ? <val_one> : <val_two> : <val_three>

Or in other words/different example:

var.true_false_other ? var.true_statement : var.false_statement : var.other_statement

Is something like that possible?

EDIT: Adding an Example, Main.tf:

resource "azurerm_subnet" "subnet" {
  for_each = var.true_false_other ? var.subnet1 : var.subnet2 : var.subnet3
  name     = each.value["subnet"]
  resource_group_name  = azurerm_resource_group.example.name
  virtual_network_name = azurerm_virtual_network.vnet-example.name
  address_prefixes     = [each.value["address_prefixes"]] 
}

variable.tf:

variable "subnet1" {
   description = "Subnet 1 variable"
}
variable "subnet2" {
   description = "Subnet 2 variable"
}
variable "subnet3" {
   description = "Subnet 3 variable"
}

tfvars:

subnet1 = { 
  subnet1A-reference  = {
    subnet      = "subnet1A"
    address_prefixes = "x.x.x.x/24" 
  },   
  subnet1B-reference    = { 
    subnet      = "subnet1B"
    address_prefixes   = "x.x.x.y/24"   
  }
}
subnet2 = { 
  subnet2A-reference  = {
    subnet      = "subnet2A"
    address_prefixes = "x.x.x.x/24" 
  },   
  subnet2B-reference    = { 
    subnet      = "subnet2B"
    address_prefixes   = "x.x.x.y/24"   
  }
}
subnet3 = { 
  subnet3A-reference  = {
    subnet      = "subnet3A"
    address_prefixes = "x.x.x.x/24" 
  },   
  subnet3B-reference    = { 
    subnet      = "subnet3B"
    address_prefixes   = "x.x.x.y/24"   
  }
}

So essentially, depending on what I tell terraform, I want it to pick one of the 3 options and only 1 of the 3. Is there a way I can tell it to pick only 1 of the variables?

like image 718
aseb Avatar asked May 03 '26 10:05

aseb


1 Answers

I wanted to define a subnet name based on the Level_tag variable. Instead of a conditional, this is what I ended up with:

variable "Level_tag" {
    type = string
    default = "Development
}

locals {
  Level_map = {
    "Development" = "DevelopmentInstances"
    "Staging"     = "StagingInstances"
    "Production"  = "ProductionInstances"
  }
}
data "aws_subnet" "subnet" {
  vpc_id = data.aws_vpc.vpc.id
  tags = {
    Name = local.Level_map[var.Level_tag]
  }
}
like image 129
Odysseas Avatar answered May 07 '26 10:05

Odysseas