How to Write if/Else Statements in Terraform


If/Else statements are conditional statements that perform decisions based on some known state, or variable.

Terraform allows you to perform these if/else statements using a ternary operation which have become popular as short-form if/else statements in many programming languages.

Where a language would write something similar to:

let truthy = false
if (something == "value") {
  truthy = true
} else {
  truthy = false
}

The ternary alternative would be:

let truthy = something == "value" ? true : false

Or even more simplified:

let truthy = something == "value"

If/Else in Terraform – Using a Ternary

As Terraform only gives the option of using a ternary, the following could be used:

vpc_config {
  subnet_ids = (var.env == "dev") ? [data.aws_subnets.devsubnets.ids[0]] : [data.aws_subnets.prodsubnets.ids[0]]
}

You can make it more readable by breaking it into multiple lines.

Note that to add a multiline ternary, you need to wrap the statement in brackets (...)

vpc_config {
  subnet_ids = (
    (var.env == "dev") ?
    [data.aws_subnets.devsubnets.ids[0]] :
    [data.aws_subnets.prodsubnets.ids[0]]
  )
}

Adding multiple If/Else statements in a single block

The above works well if you have a single conditional, but if you need multiple conditionals, then you will need to do the following:

vpc_config {
  subnet_ids = (
    (var.env == "dev") ?
      [data.aws_subnets.devsubnets.ids[0]] :
    (var.env == "uat" ?
      [data.aws_subnets.uatsubnets.ids[0]] :
      [data.aws_subnets.prodsubnets.ids[0]]
    )
  )
}