Writing Conditionals in OpenTofu
One of the things that comes up a lot when I talk about OpenTofu (formerly Terraform) configs is how to address conditionals. As of version 1.6.0 and any previous version, conditionals in the if/else
sense aren't supported in HCL.
Instead, we get to use ternaries. If you're not familiar, ternaries are a statement that looks at the truthiness of a statement and offers two possible outcomes - one if the statement evaluates to true
, and the other if the statement evaluates to false
:
provider "aws" {
region = var.env == "prod" ? "us-east-2" : "us-west-2"
}
In this example, if var.env
is "prod"
, then the AWS region will be set to "us-east-2"
. If var.env
is anything else but "prod"
, then the AWS region will be set to "us-west-2"
.
You may then be wondering how we can write the equivalent of an else if
. This is where things get ugly.
If we consider that the false-case result is the equivalent of else
(that is, in the example above, "us-west-2"
), then we can accomplish an else if
by offering another ternary:
provider "aws" {
region = var.env == "prod" ? "us-east-2" : var.env == "stage" ? "us-west-2" : "us-west-1"
}
That is not pleasant to look at, and I'd recommend avoiding it if you can. The easiest way to do so is to add more variables:
provider "aws" {
region = var.region
}
It may seem obvious to some, but I've seen plenty of codebases hinge multiple conditionals on a single variable like the string value of var.env
.
When you have multiple environments, each environment can have its own .tfvars
file, which can be targetted during plan
and apply
, e.g.:
$ tofu plan --var-file ./vars/prod.tfvars
Subscribe to my newsletter
Read articles from Colin J Lacy directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by