Terraform is a declarative language. As discussed in Chapter 1, 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, since 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, a meta-parameter called
count, a lifecycle block
create_before_destroy, a ternary operator, plus a large number of interpolation functions—that allow you
to do certain types of loops, if-statements, and zero-downtime deployments. You probably won’t need to use these too
often, but when you do, it’s good to be aware of what’s possible and what the gotchas are. Here are the topics I’ll
cover in this chapter: