Local_files created over and over - azure devops

Hi!

I have a module that takes in a bunch of variables. Does a bunch of things and then outputs specific values into a local_file. This file is then published as an artifact in azure devops, and the file has to have a static name(needs to be consumed by another pipeline).

Now, the issue is the module is used several times. Meaning terraform creates one file for every time the module is created.

So when a new module block is added, I need to ensure that only the information from THAT use, is published as an artifact.

Does anyone have an idea what I can do here?

Cheers.

Hi @chfrodin1,

I would typically recommend against having Terarform configurations directly create local files on disk, as opposed to exporting results via output values, though I do understand that sometimes generating a file is the best option.

With that said then, I’m going to describe two different strategies, one of which fits in with my recommendation, and the other which is a compromise for if you really do need Terraform to create the file.


If you can return the data you want to archive as an output value, you can use terraform output -raw OUTPUT_NAME >filename to capture the output value to a file as a separate step after running Terraform, and thus have your automation be responsible for choosing suitable filenames.

For example, if you declare an output value like the following in your root module:

output "something_result" {
  value = module.something.result
}

…you could write this “something result” to a file called something.txt as a separate step, like this:

terraform output -raw something_result >something.txt

This approach has the advantage that the Terraform configuration only needs to worry about producing the necessary data, and the details of getting that into a suitable place for your automation to capture it can be handled by the automation itself.


If you can’t avoid your module being responsible for creating a file itself, I would suggest making the output filename be an input variable to the module, rather than having the module choose a filename itself:

variable "output_filename" {
  type = string
}

resource "local_file" "example" {
  filename = var.output_filename
  # ...
}

With this strategy, you can make sure that each call to the module uses a separate filename, chosen by the root module.


I hope I understood correctly what you were asking about here. I’m afraid I’m not familiar with Azure DevOps, so I’m sorry if I missed something that seems obvious within the context of that service; my answer here is general advice about using Terraform to generate files in an automated workflow, not focused on Azure DevOps in particular.