Hot Summer Sale - up to 36% OFF

How to Use Variables in Terraform [With Examples]

How to Use Variables in Terraform [With Examples]
Published on Jul 28, 2025 Updated on Jul 28, 2025

In Terraform, variables store values, including provider authentication credentials, IP addresses, usernames, server instances to be created, and various properties of the cloud resources.

This article teaches you about different types of variables, how to define them, and how to use them in Terraform with examples. You will also learn how to properly organize variables in your Terraform project through common best practices.

#Prerequisites

To follow along in this guide, ensure you have the following:

  • A Linux machine with Terraform installed.

Follow this guide to check out how to install Terraform on Ubuntu.

#What is Terraform?

Terraform is an Infrastructure As a code (IaC) solution for creating and managing resources on the cloud through human-readable configuration files. It provides a three-phase practical workflow that makes it easy to provision resources on the cloud in a couple of seconds.

Terraform uses the Hashicorp Configuration Language (HCL) to automatically provision and manage cloud resources in an organized and reproducible way. By all means it’s a valuable tool for DevOps teams in streamlining the deployment of resources, both on-premise and on the cloud, without much effort.

Deploy, manage, and orchestrate your cloud infrastructure across one or more cloud providers with Cherry Servers Terraform module

#What are Terraform variables?

Traditional programming languages use variables to store values. For example, you pass a variable as an argument to a function and wait for it to return a result based on the input. Terraform makes use of variables in its configuration files in a similar way.

Variables in Terraform are classified into two main groups:

  • Input variables are similar to input arguments inside a function in a programming language.

  • Output variables are similar to the return values of a function in a programming language. The code snippet below shows a Python function that takes two arguments and returns their sum.


def find_sum(a, b):
	sum = a + b
	return sum

a and b would be input variables in Terraform while sum would be an output variable.

Input variables in Terraform help to:

  • Avoid hardcoding values in your Terraform configuration scripts.
  • Provide default values in Terraform configuration scripts and avoid repetitiveness.
  • Make the Terraform configurations reusable.
  • Make it easier to update and maintain Terraform configurations in the future.

Output variables in Terraform help to display information on the console. They’re mostly used to display the details of a resource in the cloud infrastructure.

#The syntax of a variable in Terraform

The input and output variables in Terraform are declared with a specific syntax.

#The syntax of an input variable in Terraform

The declaration of an input variable in Terraform is straightforward.

The variable keyword, along with a distinct and unique label, is used to define the variable. Parameters such as type, default, description, validation, nullable, and sensitive describe the behavior of a variable in Terraform and provide further information on the type of context it should be used. You declare each one of them within the curly braces.

Variables in Terraform are declared within the .tf files. The following code snippet defines a variable of type string with a default value of “cherryservers”. There is also a description that gives further information on the purpose of the variable.


variable  "cherryservers_var" {
   type = string
   default = "cherryservers"
   description = "This variable stores the name of the server."
}

In the input variable block, the type argument is required, while the default parameter is optional. Among other optional arguments that belong to a Terraform input variable, we can mention:

  • nullable: specifies if the variable’s value can be null or not.
  • validation: is used to create rules to validate the behavior of the variable.
  • sensitive: is used to store data that you don’t want to expose to the console.
  • description: provides a piece of more detailed information on the purpose of the variable.

#The syntax of an output variable in Terraform

Output variables are used to display information to the console for debugging purposes. Instead of specifying the variable directive as we saw in the previous example, an output variable in Terraform is declared with the output keyword.

The following code snippet shows how to use an output variable in Terraform.


output "cherryservers_output" {

   value = "This is an output variable."
}

Just like an input variable, an output variable in Terraform has configuration parameters inside the curly braces. In the above code snippet,we assign string data to the variable cherryservers_output with the help of the value parameter.

#How to call a variable in Terraform

It is crucial to know how to call a variable before you can use it in your Terraform scripts. To call a variable in Terraform, use the var keyword followed by the name of the variable.


var.cherryservers_var

The above code references the variable cherryservers_var, which we have defined as an input variable in Terraform in one of the previous code snippets.

#How to use variables in Terraform with examples

This section teaches you how to use variables in Terraform in easy-to-follow steps. Before going any further, open a new terminal console and type:


mkdir ~/terraform_vars && cd ~/terraform_vars

Next, create the main Terraform file known as main.tf. This helps you store Terraform variables so we can run examples.


touch main.tf

To initialize the current working directory as a Terraform project type:


terraform init

With the working directory and the main.tf file in place, follow the next steps.

#Step 1: How to declare a string variable in Terraform

In Terraform a variable of type string is usually used to store the names of cloud resources along with their properties to be created and managed. For example, to create an IP resource on Cherry Servers, use the string variable to store its region. A variable of type string is used to store a text-based value.

To declare a string variable in Terraform, use the type=string directive as shown below in the main.tf configuration file.


variable "region_ip" {

   type = string
   default = "eu_nord_1"
   description = "The region for the IP resource."
}

output "region_ip_out" {

value = "This is the region for the IP resource: ${var.region_ip}"

}

how to define a string variable in terraform

To execute the above code type:


terraform apply

how to create a string variable in terraform

The figure above shows the value of the region_ip variable displayed on the console. The output variable region_ip_out helped us display the value of the input variable on the console.

#Step 2: How to declare an integer and float variable in Terraform

Computer programming languages make a clear distinction between floats and integers. On the contrary, Terraform has a common type for both of them.

In Terraform, to declare a variable of type float or integer, use the type=number directive as shown.


variable "float_var" {
   type = number
   default = 2.5
   description = "This is a fractional."
}

output "float_point" {

 value = "This is the float point: ${var.float_var}"

}

or


variable "int_var" {
   type = number
   default = 2
   description = "A variable of type int."
}


output "int_var_out" {

 value = "This is the value of int_var: ${var.int_var}"

}

Replace the current code in the main.tf file with one of the above snippets and type:


terraform apply

how to define a float and integer variable in terraform

#Step 3: How to declare a boolean variable in Terraform

In programming, Boolean values are either True or False, just like a bulb that can be turned either Off or On. The same concept applies to Terraform. Boolean values are initialized as either True or False.

To declare a boolean variable in Terraform use the type=bool directive as shown below. Here, the default value sets it to True.

variable "ssh_port" {
  type = bool
  default = true
  description = "Determines if the ssh port should be opened or not."
}

output "ssh_port_state" {

 value = "ssh port open: ${var.ssh_port}"

}

Replace the current code in the main.tf file with the above code snippet.

To execute the above code type:


terraform apply 

how to declare a boolean variable in terraform

You can also set the default value of the ssh_port variable to false by setting default value to False. The output would look as shown below.

how to define a boolean variable with the false value in terraform

The values of variables in Terraform can also be overridden in different ways.

#Step 4: How to declare a list variable in Terraform

Like in programming languages, lists in Terraform store multiple values or elements. Each element in a list is identified by an index, with the first element having an index of 0. The difference between lists in Python and Terraform is that Python lists accept different data types ( a combination of strings, integers, etc ) while Terraform stores elements of the same data type only. For example, only strings or numbers are used per list.

To declare a variable of type list in Terraform use the type=list(string) syntax shown below.


variable "vps_users"  {
   type = list(string)
   default = ["admin1", "admin2", "user1", "user2",   "root"]
   description = "The names for the users to be created."

}

output "vps_users_out" {
  value = [for u in var.vps_users:u]
}

To execute the above Terraform code type:


terraform apply

how to define a list in terraform

The above list stores information on each one of the usernames to be created. It takes a simple for loop to go through each string in the above list and create every single one of the users.

As you can see, a list in Terraform is a composite of many elements of the same type. To store other types of values inside a Terraform list, specify it with the help of one of the following:

  • type = list(string) stores elements of type string.
  • type = list(number) Stores integers and floats.
  • type = list(bool) Stores true and false values.

You can access a specific list element by setting the value directive as shown:


value = var.vps_users[0] # retrieves the first element in the vps_users list
value = var.vps_users[1] # retrieves the second element in the vps_users list.

The hash symbol in Terraform is used to create inline comments. It’s the same as in Python.

#Step 5: How to declare a tuple variable in Terraform

Just like a list, a tuple in Terraform can store multiple values. It is a collection of ordered and immutable values declared with the square brackets. Although very similar to lists, the key difference is that tuples in Terraform can hold values of different types.

To define a variable of type tuple in Terraform use the type=tuple([number, number, string, string]) syntax.

Replace the current code in main.tf with the following code snippet.


  variable "cherry_tuple"  {
    type = tuple([number, number, string, string])
    default = [1, 1.0, "first_string", "second_string"]

}

output "tuple_el_out" {
        value = [for s in var.cherry_tuple:s]
 }

From the above code snippet, we specify the data type for each element inside the tuple.

To execute the above code type:

terraform apply

how to declare a tuple variable in terraform

Like lists, tuples in Terraform support indexing.

#Step 6: How to declare a map variable in Terraform

A map variable in Terraform is used to connect keys with values. Each of the key-value pairs in a Terraform map should be of the same data type to be declared during the variable's definition.

Similar to a dictionary in Python, you declare key-value pairs within the curly braces.


d = {"name": "cherry":  "lastname": "servers", "status": "online"}

Each key must be unique.

A practical use case of a map variable in Terraform is the creation of tags for a cloud resource.



variable "cherryservers_tags" {

  type = map(string)
  default = {
          	name = "prod_server"
          	environment = "production"    	 
          	}
  description = "Tags of the production server."

}

output "cherryservers_tags_out" {
    value = var.cherryservers_tags 
}

To execute the above code in Terraform type:


terraform apply 

how to define a map variable in terraform

In the above example, the variable of the type map can hold only values of the type string. If you want to store a different datatype for the values, specify it using the type = map() syntax.

You can specify the following datatypes for the values within a Terraform's map:

  • type = map(string)
  • type = map(number)
  • type = map(bool)
  • type = map(list)
  • type = map(set)
  • type = map(object)

To access a specific element of a map variable in Terraform, you perform a lookup based on its key.


var.cherryservers_tags["name"]

or


var.cherryservers_tags["environment"]

As you can see from the two code snippets above, the map in Terraform is very similar to a dictionary in Python.

#Step 7: How to organize variables in Terraform with the variables.tf and outputs.tf file

In a real-world scenario, Terraform configurations store and use dozens of variables. A common practice when dealing with input variables in Terraform is to define them in a separate file called variables.tf. In addition to making the Terraform configuration file more readable, this segregation makes it easier to declare and manage variables in the future.

The syntax for defining Terraform variables inside the variables.tf file is the same as before. The type, description, and default parameters are declared inside the variable block within the curly braces.

Create a new directory with the following command.

mkdir ~/terra_scripts

Navigate to the directory you just created with the help of the command below.

cd ~/terra_scripts

Create a new file named main.tf with the touch command.

touch main.tf

Since we are defining variables in a separate file, we will leave the main.tf file empty.

To initialize the current working directory as a Terraform project type:


terraform init

Then create the variables.tf file.


nano variables.tf

Then copy and paste all the input variables we have defined in the above steps inside the variables.tf file.


variable "region_ip" {

   type = string
   default = "eu_nord_1"
   description = "The region for the IP resource."
}

variable "float_var" {
   type = number
   default = 2.5
   description = "This is a fractional."
}

variable "int_var" {
   type = number
   default = 2
   description = "A variable of type int."
}

variable "ssh_port" {
  type = bool
  description = "Determines if the ssh port should be opened or not."
  default = true
}

variable "vps_users"  {
   type = list(string)
   default = ["admin1", "admin2", "user1", "user2",   "root"]
   description = "The names for the users to be created."

}

variable "cherry_tuple"  {

    	type = tuple([number, number, string, string])
    	default = [1, 1.0, "first_string", "second_string"]

}

variable "cherryservers_tags" {

  type = map(string)
  default = {
          	name = "prod_server"
          	environment = "production"
             	}
}

how to define terraform variables in variables.tf file

As for the output variables in Terraform, it is recommended to place them inside a file named outputs.tf by convention. Not only does this make the code easier to read, but it also helps in the debugging process.

With Nano editor or your favorite text editor create the outputs.tf file inside the ~/terra_scripts directory.


nano outputs.tf 

Copy and paste the output variables to outputs.tf file as shown below.


output "region_ip_out" {

 value = "This is the region for the IP resource: ${var.region_ip}"

}

output "float_point" {

 value = "This is the float point: ${var.float_var}"

}

output "int_var_out" {

 value = "This is the value of int_var: ${var.int_var}"

}

output "ssh_port_state" {

 value = "ssh port open: ${var.ssh_port}"

}

output "vps_users_out" {
  value = [for u in var.vps_users:u]
}

output "tuple_el_out" {
    	value = [for s in var.cherry_tuple:s]
 }

output "cherryservers_tags_out" {
	value = var.cherryservers_tags
}

how to define terraform output variables with outputs.tf file

Once you have declared all the input variables inside the variables.tf file, and all the output variables inside the outputs.tf preview the changes in your cloud infrastructure with the help of the terraform plan command, as shown below.



terraform plan

To apply the changes to your cloud infrastructure with Terraform type:


terraform apply

The above command executes the Terraform configuration with the default values placed in the variables.tf file.

how to organize variables in terraform with variables.tf file

The following section teaches how to provide custom values for the input variables inside the variables.tf file.

#Step 8: How to provide custom values for variables with the terraform.tfvars file

Terraform recommends tfvars files to assign custom values to the variables defined inside the variables.tf file. Use the Nano editor or your favorite text editor to create a file named terraform.tfvars inside the ~/terra_scripts directory.


nano ~/terra_scripts/terraform.tfvars

In the same way, you assign a value to a variable in a computer programming language, you must fill data inside the terraform.tfvars file. The image below helps to illustrate variable value assignment inside the terraform.tfvars file in practice.

how to provide custom values to variables with terraform.tfvars file

To preview the changes Terraform will perform in your cloud infrastructure type:


terraform plan

To apply changes with Terraform to your cloud infrastructure type:


terraform apply

The image below illustrates the effect of the terraform.tfvars file.

how to use terraform.tfvars in terraform

The values assigned to the variables inside the terraform.tfvars file are superior in precedence to the default ones defined inside the variables.tf file.

By convention, values for your Terraform variables are customized with the help of the terraform.tfvars. Apart from this file being autoloaded by Terraform by default, any file ending in .auto.tfvars or .auto.tfvars.json takes precedence over the variables.tf file.

#Step 9: How to provide custom values to variables.tf with the --var-file command line flag

The --var-file command line flag in Terraform explicitly specifies the file from which the values for the variables should be referenced. To see this command line option in action create a new file with the .tfvars suffix inside the directory where your main.tf and variables.tf files reside and assign custom values to variables inside it.


nano ~/terra_scripts/new_vars.tfvars

The image below illustrates the assignment of custom values to the variables that have been defined in the variables.tf file.

how to use the -var-file flag in terraform

To make use of the --var-file flag during the execution of the terraform apply command type:


terraform apply --var-file new_vars.tfvars

how to specify a custom file for variables with the -var-file command line flag  in terraform

During the execution, Terraform overrides the variable.tf file, and instead, references the new_vars.tfvars file. This is demonstrated in the output below.

how to use -var-file in terraform to specify a custom file for variables

The result shown above is also proof that the --var-file command line flag in Terraform is superior in variable precedence than the terraform.tfvars file.

Both variables.tf and .tfvars files store variables required for provisioning and managing cloud infrastructure with Terraform. The main difference between the two is that the former serves as a structure for the definition of the variables while the latter is used to override the default values with custom ones.

#A real-world scenario of .tfvars files usage in Terraform

A common usage of the tfvars files are when dealing with the same variables in different environments. In the development phase, you may deploy servers with a cheaper plan to save money, but in the production phase, you probably need to upgrade.

To be more practical consider the following files.

variables.tf

variable "server_plan" {

  type = string
  default = "medium"
  description = "Stores the plan for the cloud server."
}

dev.tfvars


server_plan = "small"

prod.tfvars



server_plan = "large"

The structure of the variables in the above code snippets is the same. The reason for having both dev.tfvars and prod.tfvars assign different values for the same variable is that the server instance during the development phase can be a cheap one, and in production, it should be upgraded.

You can provision different environments to your cloud infrastructure by using different .tfvars files with the help of the --var-file Terraform’s command line switch.

For example, during the production stage, you need to use the dev.tfvars as below:


terraform apply --var-file dev.tfvars

In production, you use the values of variables inside the prod.tfvars file.


terraform apply --var-file prod.tfvars

It's obvious that the above way of structuring the variable files in Terraform increases the efficiency, and organization and reduces the errors during the provisioning of cloud infrastructure in the development and production phases.

#Step 10: How to use environment variables in Terraform

Terraform supports the use of environment variables to set up custom values for the defaults inside the variables.tf file. It’s very common for cloud infrastructure engineers to store sensitive credentials as environment variables while working with Terraform. Such an approach guarantees that you keep your secret authentication keys stored on your local machine.

Let’s see an example of how to use environment variables in Terraform.

Create a new directory with the following command.


mkdir terra_env_vars && cd terra_env_vars

Then create the variables.tf file with Nano editor or your favorite text editor.


nano variables.tf

Define the api_key as a variable of type string inside the variables.tf file.


variable "api_key" {
  type = string
}

Create the outputs.tf file to store the output variables in Terraform.


nano outputs.tf 

Define the output variable api_key_out as below.


output "api_key_out" {
    value = var.api_key
} 

In outputs.tf we define an output variable to display the value of the api_key on the console. We call the variable with the var.api_key syntax.

To assign a custom value through environment variables prefix the variable api_key you have inside variables.tf with TF_VAR_ as below.


export   TF_VAR_api_key = "put you api key here" 

The image below illustrates how to assign a value to an environment variable in Terraform.

how to use environment variables in terraform

To apply the changes with Terraform type:


terraform apply

how to store credentials with terraform environment variables

The figure above illustrates that the value we assigned with the help of the TF_VAR_api_key environment variable is picked up by Terraform as a custom value for the variable api_key.

Using the TF_VAR_ we can easily prefix any sensitive variable defined in the variables.tf file and provide custom values for them through environment variables.

#Step 10.1: How to configure the CherryServers provider's credentials with environment variables in Terraform

Using environment variables provides a secure method to configure authentication credentials for a provider inside the Terraform framework.

To define the Cherry Servers authentication key as an environment variable in a Linux-based operating system type:


export CHERRY_AUTH_KEY="your cherry servers authentication key here"

With the credentials configured through the environment variables, you can now define the Cherry Servers provider, as shown below.


provider cherryservers {

}

Instead of having the Cherry Servers provider credentials hardcoded inside your configuration file or placed inside variables.tf file, it's a good practice to use them with the help of the environment variables safely.

#Final thoughts

Infrastructure engineers find variables in Terraform very useful to set up and manage cloud resources dynamically. Terraform variables provide a mechanism to make the code reusable and easily maintainable. This article guided you through enough examples to build a solid foundation on variables and their usage in Terraform.

With the knowledge acquired through this article, you can ease the deployment of your applications with Cherry Servers cloud infrastructure. Our DevOps integrations make it easy for a beginner to take full advantage of automation in the cloud.

Pick your plan based on your budget and needs, and do your cloud infrastructure provisioning quicker with our predefined Terraform scripts. You can start with Cherry Server’s general cloud VPS server, which is perfectly suited for small websites, microservices, and development environments.

Cloud VPS Hosting

Starting at just $3.24 / month, get virtual servers with top-tier performance.

Share this article

Related Articles

Published on May 28, 2025 Updated on May 28, 2025

Terraform Cheat Sheet: Terraform Command Guide

Explore essential Terraform commands with examples in this cheat sheet. Learn to initialize, plan, apply, and manage cloud infrastructure efficiently.

Read More
Published on Nov 27, 2024 Updated on Jun 9, 2025

How to Create a Terraform Configuration: Beginner's Guide

Learn how to create your first Terraform configuration with this beginner's guide. Automate cloud infrastructure, follow best practices and manage resources with ease.

Read More
Published on Dec 13, 2024 Updated on Jun 9, 2025

Terraform Registry Guide: How to Use Terraform Modules?

Learn to use Terraform Registry modules for efficient, reusable, and scalable infrastructure management. Explore tips on customization, best practices, and troubleshooting.

Read More
We use cookies to ensure seamless user experience for our website. Required cookies - technical, functional and analytical - are set automatically. Please accept the use of targeted cookies to ensure the best marketing experience for your user journey. You may revoke your consent at any time through our Cookie Policy.
build: 210eadeea.1311