Search code examples
terraform

Does adding count to a module/resource change the resource?


I have a bunch of modules. I want to change them all from

module "foo" {
  # whatever
}

to

module "foo" {
  count = 1 # because I want to make creating the module conditional, and this is the only way to do it
  # whatever
}

terraform plan tells me it's going to tear down all the resources these modules create and create new ones, presumably because a resource with a count of 1 is not the same as a resource that doesn't have a count, right? Is there a way to avoid this?


Solution

  • Unfortunately, using for_each or count in modules always changes the resource addresses in Terraform, which will lead to recreation of resources (unless you all terraform state mv them).

    Assuming you are using your own modules here and no 3rd party modules, you can resolve it by adding a condition in each of the resources within the module.

    i.e.

    module "foo" {
      create_module_foo = false
      # whatever
    }
    

    In (all of) the resources within the module, add a condition like:

       resource "foo1" "default" {
         for_each = var.create_module_foo ? {for foo1 in var.foo1 : foo1.name => foo1 } : {}
         # whatever
    

    This will not change the resource addresses