Chapter 5. Terraform Tips and Tricks: Loops, If-Statements, Deployment, and Gotchas
Terraform is a declarative language. As discussed in Chapter 1, IaC 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? Finally, how do you express an inherently procedural idea, such as a zero-downtime deployment, in a declarative language?
Fortunately, Terraform provides a few primitives—namely, the meta-parameter count
, for_each
and for
expressions, a ternary operator, a lifecycle block called create_before_destroy
, and a large number of
functions—that allow you to do certain types of loops, if-statements, and zero-downtime deployments. Here are
the topics I’ll cover in this chapter:
-
Loops
-
Conditionals
-
Zero-downtime deployment
-
Terraform gotchas
Example Code
As a reminder, you can find all of the code examples in the book on GitHub.
Loops
Terraform offers several ...
Get Terraform: Up and Running, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.