Terraform count vs. for_each

Don't count on it

Terraform has two mechanisms for provisioning multiple resources (and modules since version 0.13): count and for_each. The count feature predates for_each. Now that for_each is available, there is no reason to use count. The Terraform documentation says “If your instances are almost identical, count is appropriate. If some of their arguments need distinct values that can’t be directly derived from an integer, it’s safer to use for_each.” This is bad advice. [Read More]

Terraform Modules as Functions

Using no-resource modules to build config maps

How do you create user-defined functions in Terraform? The definition of a module in terraform resembles that of a function with side effects implemented through resources. We use zero-resource modules as Terraform functions. Below is a simple example use of for_each_slice taking input from var.config.hosts. For each element in the input map it slices out the corresponding value the named keys, throwing an error for missing keys or keys that fail a requirement, such as being a non-empty string. [Read More]