Conditional nested configuration blocks for Terraform Resources

Rees Pozzi
3 min readFeb 3, 2023

Conditional expressions are used to add logic-based decision making with code. This usually follows a certain flow that is extensible and changes our code configuration based on certain conditions being met.

if (some condition is true) then
Do one thing!
else
Do a different thing!

Terraform is a little different to most programming languages though, a declarative IAC tool delivered by HashiCorp, which is written in HCL or JSON.

Does Terraform support conditional logic?

Yes, but it’s a little different to what you may be used to, or expect to be writing. Terraform uses conditional expressions, basically a ternary operator. You can read more about them here, but generally the form looks like this:

condition ? true_value : false_value

This is great for simple use cases, like deciding a value for an attribute, number of resources to create, etc. But what about when we want an entire nested block with complex values to either be included or omitted, based on a condition? Can we write all of this nicely within one line?

Recently, I’ve come across this interesting problem that goes beyond Terraform’s general use case for conditional expressions, and spent some time looking through solutions with colleagues. Let’s say you have a resource managed by Terraform, like below:

--

--