Variables in Terraform are like in any other programming or scripting language; they hold values. Variables can hold many different types of information to call on later in a configuration file.

Variable definition syntax

Variables are handy HCL constructs that can be defined in a few different ways and in a few different places.

Blocks

Variables can be defined in a block with various arguments in the form:

variable "<variable name>" {
    type = <type> ## string, number or bool
    <default = <value>>
    <description = "">
}

You can find more information about each type of argument assigned to a variable in the Input Variables Terraform documentation.

Let’s say you’re creating a configuration to provision an Azure VM from scratch. Inside of that configuration, you are referencing the VM name in various places. To ensure you only have a single place to change, if that VM name should change, you’ve decided to create a variable.

The below example defines a variable called virtualMachineName and assigns it a default value of NoBSVM. Since NoBSVM is text, the variable sets a type of string.

variable "virtualMachineName" {
	type = string
	default = "NoBSVM"
}

Assigning default values to variables isn’t necessarily best practice. Why? It is because you are statically assigning a value to the variable that is tied to a specific name.

“Simple” syntax

The above example (of defining an Azure VM name) created a variable called virtualMachineName and assigned it a value of NoBSVM in a block with four lines of code. This approach wasn’t entirely necessary. Since the variable definition was a simple string, it could have been represented in “shorthand” syntax like below.

variable "virtualMachineName" = "NoBSVM"

You can see that this approach saves a little typing yet performs the same function.

At runtime

Whenever Terraform runs, you can also create variables without defining them in a file at all. When you run the Terraform binary, you can add an additional argument, creating a variable on the fly that is then available in the configuration.

All variables that are run from the command-line start with the -var switch. Following the switch, there is an = sign to define the variable and a key-value pair representing the variable name and value. You can see an example of the syntax on defining a virtualMachineName variable at runtime below.

> terraform apply -var="virtualMachineName=NoBS-VM"

Get hands-on with 1200+ tech skills courses.