Terraform: module for conditional include of related resources

If you have a set of resources in Terraform that are conditionally included based on the same criteria, instead of appending a “count/for_each” on every resource definition, consider refactoring them into a module.

The conditional can then be placed on the module definition instead of polluting each resource definition.

For example, if you had several resources each relying on a shared “make_file” boolean to determine their inclusion, this could be written like below (but is repetitive and not easy to maintain).

locals {
  # conditional shared by multiple resources
  make_file = true
}

resource "local_file" "myfile1" {
  count = local.make_file ? 1 : 0
  content  = "This is myfile1"
  filename = "myfile1.txt"
}

resource "local_file" "myfile2" {
  count = local.make_file ? 1 : 0
  content  = "This is myfile2"
  filename = "myfile2.txt"
}

resource "local_file" "myfile3" {
  count = local.make_file ? 1 : 0
  content  = "This is myfile3"
  filename = "myfile3.txt"
}

This is repetitive, hard to maintain, and also hijacks the conditional of each resource definition for this one specific purpose.  When resources become more complex and require their own logic for “count” or need to use “for_each”, it is now unavailable for any other purpose.

Solution: use module conditional

A way to address these shortcomings is to refactor these resources into their own module.  And then the conditional can be placed directly on the module definition (instead of each resource).

For example, your main.tf could look like below.

# module containing the three resources originally defined at main level
module "mymod" {
  source = "./my-module"
  # conditional placed at module level now
  count = local.make_file ? 1 : 0
}

And your “my-module/main.tf” would contain the three original resources, but notice none of them need their own conditional.

resource "local_file" "myfile1" {
  content  = "This is myfile1"
  filename = "myfile1.txt"
}

resource "local_file" "myfile2" {
  content  = "This is myfile2"
  filename = "myfile2.txt"
}

resource "local_file" "myfile3" {
  content  = "This is myfile3"
  filename = "myfile3.txt"
}

These resources are now free to use the count/for_each clauses for their own more advanced logic purposes.

REFERENCES

Terraform modules

github, tf-module-for-conditional project code