4 Expressions and iterations

 

This chapter covers

  • Modifying data through the use of expressions and functions
  • Operators and their uses
  • Some of the most commonly used functions
  • String generation using templates
  • Multiplying resources with for_each and count
  • Iterating over and transforming objects and lists

So far in our quest to learn Terraform, we’ve focused on the objects of the Terraform language: the resource, data, variable, and other blocks. We’ve used those blocks to define and provision infrastructure and have even done a small amount of validation using input validation blocks.

With what we’ve learned up until this point, we can do quite a bit, but we’re still mostly using Terraform to define infrastructure and make copies of it. Our variables have given us some ability to customize our setup but only in the sense that we’re exposing a few variables to our users.

Terraform is capable of a lot more than that. It can be used to create dynamic features that can be enabled or disabled. It can calculate, derive, and transform values for use as configuration. Terraform has a rich library of reusable functions for transforming data, and it even has a templating language that can be used to build complex strings.

4.1 Expanding our module

4.1.1 Research

4.1.2 Adding a name and tags

4.1.3 Allowing multiple instances

4.1.4 Creating a role

4.1.5 Enabling the session manager

4.1.6 Reviewing our work

4.2 Operators and conditionals

4.2.1 Math

4.2.2 Comparison

4.2.3 Boolean operators

4.2.4 Conditional (Terraform’s ternary operator)

4.2.5 Order

4.3 Functions

4.3.1 Calling and using functions

4.3.2 The standard library

4.3.3 Pure vs. impure functions

4.4 Strings and templates

4.4.1 The file function