DEV Community

Cover image for Terraform Associate Certification: Conditional Expression & Local values
Daniel Huerta
Daniel Huerta

Posted on

Terraform Associate Certification: Conditional Expression & Local values

Conditional Expression

If you have programmed in other languages such as C or Javascript you may know the ternary operator. Well, in Terraform you can use it as well and it is nothing but a conditional expression that uses the value of a bool expression to select one of two values.

The syntax of it is as follows:

condition ? True_value : False_value

If condition is true, then the returned value will be True_value, otherwise will be False_value.

Let's see an example of this:

Screen Shot 2021-08-24 at 10.47.55

In this case, the amount of aws_instances will be created according to the value of the bool variable named istest. As you can see in the image, this value is set to false so only one aws_instance.prod will be created πŸ˜‰.

Local Values

A local value assigns a name to an expression, allowing it to be used multiple times within a module without repeating it.
Let's see an example to understand this better, in the next image you will see that I created a set of tags within a locals block.

Screen Shot 2021-08-24 at 10.57.19

I'm using these tags inside two different resource blocks but I'm not typing every tag on it, that's the advantage of the local values.

Local values support for expression

Local values can be used for multiple different use-cases like having a conditional expression.

Screen Shot 2021-08-24 at 10.58.47

Use local values only in moderation, in situations where a single value or result is used in many places and that value is likely to be changed in future.

Discussion (0)