Example: In Azure, I'm deploying multiple resource groups, managed disks, network interfaces, etc, all in the same region.
I want to declare a "region" primitive (a "constant"), which all these resources will reference. Which of those is following convention?
a) variables.tf:
variable "region" {
type = string
default = "a-place"
}
b) locals.tf
locals {
region = "a-place"
}
Naturally, I would choose to declare it as a local. I would only use a variable if I expect a value to come (or be overridden) from environment variables, command line, or if I were creating a module.
However, I haven't seen local being used for "declaring constants" in any examples, which makes me think that a convention exists to use locals with very limited scope (e.g. mainly for creating structures which can be of use with count and for_each constructions).
Covering my back before someone flags this as opinion based: I'm asking what the convention is, not what your opinion is that the convention should be.
Follow-up question: Would the answer be any different if this example covered IP addresses, resource name prefixes, etc. instead of region? (does the convention only cover particular fields?)
The general intent of local values is to represent expressions whose result you want to re-use in many locations in the module without duplication. That includes constant values, in situations where it's productive to factor them out e.g. because you expect them to change in future and want to change only in one place, or because the local value name is more meaningful than the value itself and thus improves readability of the parts of the configuration using it.
Declaring a local value also has a potential cost, though: it forces anyone reading the rest of the module to look somewhere else to see the final value each time you refer to it. Often the benefits outweigh that cost, but not always.
As you've noted, the intent of input variables is that they be settable by the caller of your module, so you should use input variables only if you expect the default value to be overridden sometimes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With