Use of path.module and module count with local_file

Hi,

some of our modules include creation of a file using local_file resource (filename = “${path.module}/my.json”). If this module is used using count/for_each for modules the given json file is only “available” once and not as many times as the module count is set. I couldn’t find any other unique path.module terraform expression, so I’m wondering how the given file would not get overwritten even if count > 1 is applied.

Thanks & Best.

Hi @tbugfinder,

What you’ve encountered here doesn’t seem special to local_file: when designing a module that declares managed resources we must always include a mechanism to ensure that the objects it creates are suitably unique to coexist with other instances, such as by including an input variable on the module to choose a prefix or similar additional unique identifier to use in the naming of the objects.

The “remote system” for local_file happens to be the local filesystem rather than an API accessible over the network, but the principle is the same: you must design the interface of your module to allow the caller to pass in sufficient context to make the object have a unique name. One way to achieve that would be to have the filename itself be provided by the calling module, and then the caller can arrange for the files to be created in its own directory and to include ether each.key or count.index to make it unique within its own context:

module "example" {
  source   = "./modules/example"
  for_each = var.each

  filename = "${path.module}/file-${each.key}.json"
}

If specifying the whole filename doesn’t feel right, another option would be to pass in a simpler string that will be used as part of the filename, which would then be closer to the typical pattern for creating objects in remote systems that use unique names as the primary identifier.

Hi @apparentlymart,

indeed this “issue” isn’t specific to local_file. I just started off thinking that terraform might have taken uniqueness into account while module count was added. However I couldn’t find such a pattern. Your proposal seems to be feasible for the use-case. So I’ll give that a try.

Thank You!