Terraform is a declarative language. As discussed in Part 1 of this series, infrastructure-as-code in a declarative language tends to provide a more accurate view of what’s actually deployed than a procedural language, so it’s easier to reason about and makes it easier to keep the codebase small. However, certain types of tasks are more difficult in a declarative language.
For example, because declarative languages typically don’t have for-loops, how do you repeat a piece of logic—such as creating multiple similar resources—without copy and paste? And if the declarative language doesn’t support if-statements, how can you conditionally configure resources, such as creating a Terraform module that can create certain resources for some users of that module but not for others?
Fortunately, Terraform provides a few primitives—namely, the meta-parameter count, for_each and for expressions, a ternary operator, and a large number of functions—that allow you to do certain types of loops and if-statements. Here are the topics I’ll cover in this blog post:
Loops
Conditionals
Terraform Gotchas