chapter four

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 resources, data sources, variables, 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 which 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 Add a Name and Tags

4.1.3 Allow Multiple Instances

4.1.4 Create Role

4.1.5 Enable 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 Versus Impure Functions

4.4 Strings and Templates

4.4.1 The file function

4.4.2 The templatefile function

4.4.3 String Template Language

4.4.4 The template file resource

4.4.5 When not to use Templates

4.5 Regular Expressions

4.5.1 Regex

4.5.2 Regexall

4.5.3 Replace

4.6 Type Conversion

4.6.1 Implicit Type Conversion

4.6.2 The toType functions

4.6.3 Sensitive and Nonsensitive

4.7 Try and Can

4.8 count and for_each

4.8.1 count

4.8.2 for_each

4.8.3 Accessing Attributes

4.8.4 Limitations and Workarounds