2
votes

I have been trying to conditionally use a module from the root module, so that for certain environments this module is not created. Many people claim that by setting the count in the module to either 0 or 1 using a conditional does the trick.

module "conditionally_used_module" {
  source = "./modules/my_module"
  count  = (var.create == true) ? 1 : 0
}

However, this changes the type of conditionally_used_module: instead of an object (or map) we will have a list (or tuple) containing a single object. Is there another way to achieve this, that does not imply changing the type of the module?

2
after teraform 0.13 - for_each is also supported for modules - Encho Solakov

2 Answers

0
votes

To conditionally create a module you can use a variable, lets say it's called create_module in the variables.tf file of the module conditionally_used_module.

Then for every resource inside the conditionally_used_module module you will use the count to conditionally create or not that specific resource.

The following example should work and provide you with the desired effect.

# Set a variable to know if the resources inside the module should be created
module "conditionally_used_module" {
  source = "./modules/my_module"
  create_module = var.create
}

# Inside the conditionally_used_module file
# ( ./modules/my_module/main.tf ) most likely 
# for every resource inside use the count to create or not each resource
resource "resource_type" "resource_name" {
 count = var.create_module ? 1 : 0
 ... other resource properties 
}
0
votes

The terraform-aws-eks repo shows an example to achieve what you want in the "Conditional Creation" block of the README file.