Terraform 0.12 — conditional block.

Jacek Kikiewicz
1 min readJun 4, 2019

--

I have long waited for new terraform 0.12 to be out. I had big hopes that it will resolve some issues that I had encountered as well as allow me to get rid of many workarounds that I was forced to use.
Overall it’s a big improvement, I have already upgraded my whole setup (~10–15 states) into 0.12 compatible syntax.
There is however one thing I struggled to find and it seems it’s not officialy supported — this is a conditional block.
There are manuals about new way of using variables conditionally (thanks to ‘null’ value now), there are manuals about dynamic blocks generated in loop but… nothing on conditional block.

Solution to this is a combination of dynamic block and conditional list as for_each loop input:

dynamic "block_name" {
for_each = var.some_variable == "" ? [] : [1]
content {
key1 = value1
key2 = value2
}
}

Above example will return empty list to for_each if var.some_variable is empty, and if it isn’t then it will return a list with one element which will make for_each function to generate exactly one such block.
Also, note that contents of this block don’t have to have anything to do with actual for_each loop, you can define whatever you need.

Also, have a look at my other Terraform articles on medium!

--

--