Skip to content

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 }
Code language: JavaScript (javascript)

The ternary alternative would be:

let truthy = something == "value" ? true : false
Code language: JavaScript (javascript)

Or even more simplified:

let truthy = something == "value"
Code language: JavaScript (javascript)

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]] }
Code language: plaintext (plaintext)

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]] ) }
Code language: plaintext (plaintext)

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]] ) ) }
Code language: plaintext (plaintext)

See also  Which x for that sum in Kotlin
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x