5

I have a situation where I need to store some intermediate values so I can reuse them in other parts of the root module. I know about local values and I know about null_data_source except I do not know which one is the recommended option for holding re-usable values. Both descriptions look somewhat similar to me

local values (https://www.terraform.io/docs/configuration/locals.html)

Local values can be helpful to avoid repeating the same values or expressions multiple times in a >configuration, but if overused they can also make a configuration hard to read by future >maintainers by hiding the actual values used.

and null_data_source (https://www.terraform.io/docs/providers/null/data_source.html)

The primary use-case for the null data source is to gather together collections of intermediate >values to re-use elsewhere in configuration:

So both appear to be a valid choice for this scenario.

Here is my example code

locals {
  my_string_A = "This is string A"
}

data "null_data_source" "my_string_B" {
  inputs = {
    my_string_B = "This is string B"
  }
}

output "my_output_a" {
  value = "${local.my_string_A}"
}

output "my_output_b" {
  value = "${data.null_data_source.my_string_B.outputs["my_string_B"]}"
}

Could you suggest on when to use the one over the other for holding intermediate values and what is the pros/cons of each approach?

Thank you

Mark
  • 53
  • 1
  • 4
  • As per my understanding the null data source should be used when you have a collection of intermediate values and the locals to be used when you have a fairly simple values. – error404 Oct 30 '19 at 10:49

1 Answers1

6

The null_data_source data source was introduced prior to the local values mechanism as an interim solution to meet that use-case before that capability became first-class in the language. It continues to be supported only for backward-compatibility with existing configurations using it.

All new configurations should use the Local Values mechanism instead. It's fully integrated into the Terraform language, supports values of any type (while null_data_source can support only strings), and has a much more concise/readable syntax.

Martin Atkins
  • 62,420
  • 8
  • 120
  • 138
  • I used `null_data_source` as a hack to wait for a file, as described [here](https://barneyparker.com/posts/installing-npm-dependencies-with-terraform/). I wouldn't know how to replicate that using locals. – ADTC Nov 16 '21 at 13:01
  • I'd say `null_data_source` can enjoy another life today, as a way to add validation constraints for cases where they're not supported by the language yet (e.g. modules). Though, the builtin `terraform_data` resource can also work for this purpose if you don't mind an extra resource. – kbolino Aug 11 '23 at 19:46