Learning Center
Terraform

How to Use Terraform Variables

24 Mar 2025
Hostman Team
Hostman Team

Terraform is a popular software tool for DevOps engineers and system administrators, with its primary goal being creating and managing cloud infrastructure. Its main feature is the ability to automate all processes related to infrastructure deployment.

Terraform has a set of core elements used to describe infrastructure. These include providers, resources, data sources, modules, expressions, and variables.

Variables in Terraform are special elements that allow users to store and pass values to various parts of modules without modifying the main configuration file's code. They enable flexible management of infrastructure settings and parameters, making configuration and maintenance easier.

In this guide, we’ll discuss Terraform variables and explain how to use them in your configuration.

Declaring Variables
Copy link

One can describe Terraform variables as containers where users store information (deployment region, instance types, passwords, or access keys). Their values are defined once through CLI parameters or environment variables and can be used in different parts of the configuration.

This process is usually done using the variable block in the variable definition file (variables.tf). The syntax for declaring variables is as follows:

variable "variable_name" {
  list_of_arguments
}

Each variable must have a unique name. This name is used to assign values externally and to reference the value within the module. The name can be anything but should not conflict with meta-arguments like version, providers, locals, etc.

Variable arguments are optional, but it’s important not to avoid them, as they allow users to set additional parameters. Some of the main arguments include:

  • type — Specifies the data type allowed for the variable. We’ll cover types in detail in the next chapter.
  • description — This argument allows you to add a description to explain the purpose and usage of the variable.
  • default — Defines a default value for the variable.
  • validation — Specifies custom validation rules.
  • sensitive — Controls the confidentiality of the variable in outputs.
  • nullable — Accepts two values (true and false) and indicates whether the variable can accept a null value.

Variable Type Constraints
Copy link

As mentioned earlier, for each variable in Terraform, it’s possible to specify a data type that restricts the values it can accept. This is done using the type argument.

Terraform supports the following data types:

  • number — Numeric data format (integers, floating-point numbers, etc.).
  • string — A sequence of Unicode characters for storing textual information.
  • bool — Boolean data type (True or False).
  • map or object — A collection of key-value pairs enclosed in curly braces.
  • list or tuple — A sequence of values of the same or different data types enclosed in square brackets.

Example of specifying a variable type:

variable "region" {
  type = string
}

Variable Description
Copy link

Since the input variables of a module are part of its user interface, you can briefly describe the purpose of each variable using the optional description argument. Here's an example of how to use it:

variable "region" {
  type        = string
  description = "Specifies the server region"
}

The description helps developers and other users better understand the role of the variable and what values it expects.

Custom Validation Rules
Copy link

In Terraform, you can specify custom validation rules for a selected variable using the validation argument.

Each validation must include two required arguments: condition and error_message. The condition defines an expression that checks the variable’s value, returning True if it's valid and False if it’s not. The error_message specifies the message to be displayed to the user if the condition returns False.

Example of using the validation argument:

variable "email" {
  type        = string
  description = "Email address"
  validation {
    condition           = can(regex("^\\S+@\\S+\\.\\S+$", var.email))
    error_message = "Invalid email format"
  }
}

In the above example, we validate the email variable to ensure it matches a proper email address format using a regular expression in the condition. If the email address does not pass the validation, the user will see the error message "Invalid email format."

Sensitive Data in Variables
Copy link

When using the sensitive argument, Terraform handles the variable in a way that prevents accidental exposure of sensitive data in the plan or apply outputs.

Example of using the sensitive argument:

variable "user" {
  type = object({
    name    = string
    role    = string
  })
  sensitive = true
}

resource "example_resource" "example1" {
  name = var.user.name
  role = var.user.role
}

Any resources and other Terraform elements associated with a sensitive variable also become sensitive. This is why sensitive data will not be shown in the output, as represented in the image below.

Assigning Values to Root Module Variables
Copy link

After declaring variables in the root module, you can assign values to each of them. There are several ways to do this, which we'll discuss below.

Image1

Command Line
Copy link

The first method for passing values to variables is using the command line. You can use the -var parameter when running the terraform plan or terraform apply commands. The syntax for this method is as follows:

terraform apply|plan -var="variable1=value1" -var="variable2=value2"

You can use the -var parameter multiple times in a single command.

Variable Definition Files
Copy link

You can also specify values using a special variable definition file, which must end with .tfvars or .tfvars.json. The syntax for this file is:

variable1 = "value1"
variable2 = "value2"

To use the values specified in the file, you must provide the file when running the Terraform command:

terraform apply -var-file="file_name.tfvars"

Environment Variables
Copy link

The last method we will discuss is using Terraform environment variables. The environment variable names must be in the format TF_VAR_variable_name. The syntax for this method is as follows:

export TF_VAR_variable1=value1
export TF_VAR_variable2=value2
terraform apply|plan

Conclusion
Copy link

In this guide, we explored variables in Terraform, learned how to declare them, reviewed the main arguments, and discussed methods for assigning values to them. Proper use of variables helps you create a more flexible and secure infrastructure with Terraform.