What Is A Local?
As previously stated, Terraform Locals are named values that you can refer to in your configuration. You can use local values to simplify your Terraform configuration and avoid repetition. It is important to note, that unlike variables found in programming languages, Terraform's locals don't change values during or between Terraform runs such as plan, apply, or destroy. For this reason, you can use locals to give a name to the result of any Terraform expression, and re-use that name throughout your configuration.
What Is A Variable?
The official definition of a Terraform Input Variable is that they serve as parameters for a Terraform module, allowing aspects of the module to be customized without altering the module's own source code, and allowing modules to be shared between different configurations. If you are familiar with traditional programming languages, these variables can be thought of as being like function arguments.
Being like function arguments rather than being like traditional variables in any programming language is an important distinction. As these values will be "injected" (my words) into your Terraform, where that value is used. To picture that, and using the traditional programming language school of thought, you can think of where you are using the variable (like in a module, resource, etc...) as the "parameter" and the terraform variable as the "argument" that fills the parameter of your function.
When you declare variables in the root module of your configuration, you can set their values using CLI options, environment variables, or the Terraform configuration. When you declare them in child modules, the calling module should pass values in the module block. This means, that variable name and value in child module, will be passed to the parent module, where that value will fill a variable with the corresponding name, with the value passed from the child module.
The most basic way to think about this, going to back to the traditional programming language metaphor, is local values are like a function's temporary local variables. For example, like saving off the value of something, say the result of a return value of another function, into a variable, to use it later in your current function.
As previously stated, Terraform's locals don't change values during or between Terraform runs such as plan, apply, or destroy. To add, unlike input variables, locals are not set directly by users of your configuration. So, because of this behavior, you can use locals to give a name to the result of any Terraform expression, and re-use that name throughout your configuration. by saving the value of an expression into a local, you have essentially "saved off" the return value of something else, for which unless that local is manually overridden or changed later or further down in the Terraform config, you will have whatever value that local is holding for the rest of the Terraform configuration.
Written: August 23, 2021