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:
The ternary alternative would be:
|
|
Or even more simplified:
|
|
If/Else in Terraform – Using a Ternary
As Terraform only gives the option of using a ternary, the following could be used:
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 (...)
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: