How to write If/Else Statements in Terraform

1 min read 220 words

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]]
    )
  )
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags