Working with Expressions
Learn how to calculate values for our resources using expressions.
We'll cover the following
Overview
When working with configuration files, we might need to do some computations. Expressions are used to make configuration flexible and they contain four major building blocks, which are:
- Values
- Variables
- Operators
- Functions
There are a lot of use cases for Terraform expressions, such as:
-
When we need to join or concatenate values together, we can use the
concat()
function. -
When we need to determine the length of a value, we can use the
length()
function. -
When we need to perform mathematical calculations, we can use a range of mathematical operators and numeric functions like
max()
,min()
,ceil
, and so on. -
When we need to write conditional statements, we use ternary operators.
-
When need to format a value into another value, we use the
slice()
function.
To build expressions, one of the key requirements is operators. Let’s examine the various operators that are available for use in Terraform.
Operators
For mathematical operations, there are three classifications of operators that we can use:
- Arithmetic operators (
+
,-
,*
,/
,%
): These are used for performing arithmetic operations. - Comparison operators (
>
,>=
,<
,<=
,==
,!=
): These are used to compare one value to another. - Logical operators (
&&
,||
,!
): These are used to combine two expressions together and evaluate if the value istrue
orfalse
.
In the code snippet below, we create a couple of variables using some of the operators mentioned above.
Get hands-on with 1400+ tech skills courses.