Terraform Variables and Configuration explained – 5 mins reading!

 

There are broadly 3 ways to configure/declare variables in Terraform. This section will focus on only on Input variables and Environment variables.

  1. Input variables
  2. Environment variables
  3. Personal Environment and Personal Organization variables

Input variables
Input variables as a way to parameterize Terraform configurations. Input variables serve as parameters for a Terraform module.

Understand Input variables block body
Within the Input variables block body (between { }) is configuration for the variable, which accepts the following arguments:

  • type (Optional) – If set this defines the type of the variable. Valid values are string, list, and map.
  • default (Optional) – This sets a default value for the variable. If no default is provided, Terraform will raise an error if a value is not provided by the caller.
  • description (Optional) – A human-friendly description for the variable. This is primarily for documentation for users using your Terraform configuration.

Types of Terraform Input variables?

String – String values are simple and represent a basic key to value mapping where the key is the variable name. An example is:

[code]variable "key" {
type = "string"
default = "value"
}[/code]

Lists – A list value is an ordered sequence of strings indexed by integers starting with zero. For example:

[code]variable "users" {
type = "list"
default = ["admin", "ubuntu"]
}[/code]

Maps – A map value is a lookup table from string keys to string values. This is useful for selecting a value based on some other provided value. A common use of maps is to create a table of machine images per region, as follows:

[code]variable "images" {
type = "map"
default = {
"us-east-1" = "image-1234"
"us-west-2" = "image-4567"
}
}[/code]

How to define terraform variables?
Simplest way to define a variable using “variable” keyword in any .tf file. The file can be named anything, since Terraform loads all files ending in .tf in a directory.

[code]variable "access_key" {}
variable "secret_key" {}
variable "region" {
default = "us-east-1"
}[/code]

How to use terraform variables in configuration?
Any inputs variables defined in terraform configuration file can be used using $ sign. such as

[code]provider "aws" {
access_key = "${var.access_key}"
secret_key = "${var.secret_key}"
region = "${var.region}"
}[/code]

How to assign variables?
There are multiple ways to assign Terraform variables. Below is also the order in which variable values are chosen. The following is the descending order of precedence in which variables are considered.

Method 1 – Command-line flags
You can set variables directly on the command-line with the -var flag. Any command in Terraform that inspects the configuration accepts this flag, such as apply, plan, and refresh:

[code]$ terraform apply -var 'access_key=foo' -var 'secret_key=bar'[/code]

Method 2 – From a file
To persist variable values, create a file and assign variables within this file. Create a file named terraform.tfvars with the following contents:

[code]access_key = "foo"
secret_key = "bar"

somelist = [
"one",
"two",
]

somemap = {
foo = "bar"
bax = "qux"
}[/code]

If a terraform.tfvars file is present in the current directory, Terraform automatically loads it to populate variables. If the file is named something else, you can use the -var-file flag directly to specify a file.

[code]$ terraform plan -var-file="secret.tfvars" -var-file="production.tfvars"[/code]

Method 3 – From environment variables
Terraform will read environment variables in the form of TF_VAR_name to find the value for a variable. For example, the TF_VAR_access_key variable can be set to set the access_key variable. Environment variables can only populate string-type variables. List and map type variables must be populated via one of the other mechanisms.

Method 4 – UI Input
If you execute terraform apply with certain variables unspecified, Terraform will ask you to input their values interactively. These values are not saved, but this provides a convenient workflow when getting started with Terraform.

Method 5 – Variable Defaults
If no value is assigned to a variable via any of these methods and the variable has a default key in its declaration, that value will be used for the variable.

Environment variables

TF_LOG – If set to any value, enables detailed logs to appear on stderr which is useful for debugging. For example:
export TF_LOG=TRACE

To disable, either unset it or set it to empty. When unset, logging will default to stderr. For example:
export TF_LOG=

TF_LOG_PATH – This specifies where the log should persist its output to. Note that even when TF_LOG_PATH is set, TF_LOG must be set in order for any logging to be enabled. For example, to always write the log to the directory you’re currently running terraform from:
export TF_LOG_PATH=./terraform.log

TF_INPUT – If set to “false” or “0”, causes terraform commands to behave as if the -input=false flag was specified. This is used when you want to disable prompts for variables that haven’t had their values specified. For example:
export TF_INPUT=0

TF_MODULE_DEPTH – When given a value, causes terraform commands to behave as if the -module-depth=VALUE flag was specified. By setting this to 0, for example, you enable commands such as plan and graph to display more compressed information.
export TF_MODULE_DEPTH=0

TF_VAR_name – Environment variables can be used to set variables. The environment variables must be in the format TF_VAR_name and this will be checked last for a value. For example:

export TF_VAR_region=us-west-1
export TF_VAR_ami=ami-049d8641
export TF_VAR_alist='[1,2,3]’
export TF_VAR_amap='{ foo = “bar”, baz = “qux” }’

TF_CLI_ARGS and TF_CLI_ARGS_name – The value of TF_CLI_ARGS will specify additional arguments to the command-line. This allows easier automation in CI environments as well as modifying default behavior of Terraform on your own system.

TF_DATA_DIR – TF_DATA_DIR changes the location where Terraform keeps its per-working-directory data, such as the current remote backend configuration. By default this data is written into a .terraform subdirectory of the current directory, but the path given in TF_DATA_DIR will be used instead if non-empty.

TF_SKIP_REMOTE_TESTS – This can be set prior to running the unit tests to opt-out of any tests requiring remote network connectivity. The unit tests make an attempt to automatically detect when connectivity is unavailable and skip the relevant tests, but by setting this variable you can force these tests to be skipped.

export TF_SKIP_REMOTE_TESTS=1
make test

Variable Hierarchy
It is possible to create the same variable in multiple places for more granular control. Variables are applied in the following order from least to most precedence:

  1. Environment
  2. Personal Organization
  3. Personal Environment

Undersatand variables use cases in Terraform Modules? – TBD

Reference
https://www.terraform.io/docs/configuration/environment-variables.html

Rajesh Kumar
Follow me