Explaining the Difference between Input and Local Variables in Terraform

Pavol Kutaj
2 min readSep 14

--

The aim of this pagešŸ“ is to explain how to use variables in Terraform based on the particular example of assigning values to input variables from outside of the configuration files.

  • Terraform has three types of variables: input variables, local values (locals), and outputs
  • Let’s focus on the difference between the first two, inputs versus locals
  • Input variables are parameters of a Terraform module.
  • You can set them directly in the configuration file or pass them as command-line arguments when running Terraform.
  • Local values are named expressions that you can use to avoid repeating the same values or expressions multiple times in a configuration.
  • Unlike input variables, you cannot directly assign values to locals from outside the configuration.
  • NOTE: this does not mean that locals have to be set in the very same file, the files are collected when a plan is executed, i.e. they can be located in e.g. locals.tf file
  • Instead, locals are defined within the configuration, and their values are computed based on other values or expressions within the same configuration.
  • Hashicorp docs say

Unlike input variables, locals are not set directly by users of your configuration.

— https://developer.hashicorp.com/terraform/tutorials/configuration-language/locals

  • ā€œUsers of your configurationā€ refers to anyone who is using your Terraform module or configuration.
  • I am for example a member of the Infra support team and I am setting input variables by manipulating values in the Consul KV Store
  • I and other users can provide input variables when they use modules or configuration, but we cannot directly assign values to local variables unless we manipulate config files directly
  • We can therefore assign values to input variables in several ways:
  • Command Line Flags
  • From a File
  • Environment Variables
  • Variable Defaults
  • Module Blocks
  • As said, we can also use Consul and other databases to store and retrieve variable values in Terraform.

CODE

Here is a particular example of a terraform file

variable "image_id" {
description = "The id of the machine image (AMI) to use for the server."
type = string
}

locals {
instance_type = "t2.micro"
}

resource "aws_instance" "example" {
ami = var.image_id
instance_type = local.instance_type

tags = {
Name = "example-instance"
}
}

In this example, image_id is an input variable and instance_type is a local value. The aws_instance resource uses these variables.

LINKS

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com