Terraform: How to Use Conditionals to Dynamically Create Resources

…don’t struggle looking for if/else statements, you won’t find them…

Andrea Marinaro
The Startup

--

Photo by Himesh Kumar Behera on Unsplash

As you (probably) know, Terraform doesn’t support if statements.
Luckily we can achieve the same result by using a specific parameter called count.

You can think about it this way: you can set count to 1 on a specific resource and get one copy of that resource.

However, setting the same count parameter to 0 you won’t get any resource created.

So, as already mentioned, you won’t need if/else statements at all, Terraform use conditional expressions with the following format:

<CONDITION> ? <TRUE_VAL> <FALSE_VAL>

All that Terraform does is nothing but evaluating the boolean logic in CONDITION and, based on that, if the value is true it will return TRUE_VAL otherwise it’ll return FALSE_VAL if the result is false.

Just to give you some contest, we’re migrating our existing AWS infrastructure (Ansible&Boto3 deployed) in Terraform.

This particular example is referred to ELB creation with a target group and a listener.
is taken from a migration project I’m currently working on and it will practically show what I’ve just…

--

--