How to use Terraform Variables - Locals,Input,Output



Terraform variables are a way to store values that can be reused throughout your Terraform configuration.

They allow you to define a value once and reference it in multiple places throughout your configuration, making it easier to manage and update your infrastructure.

  1. Variables are defined in the variables block in your Terraform configuration file, where you can give a name and a default value. Please refer to the following screenshot exaplaining how variables are defined inside terraform-

terraform variables string, bool, number, list, set, map

  1. Terraform variables can have various type such as string, number, boolean, list, map etc.
  2. Variables can be set in the command line when running Terraform commands using the -var flag.
  3. Variables can also be set using a separate file, called a variable file, using the -var-file flag.
  4. Variables can be accessed in Terraform configuration files using the var function, for example var.example_variable
  5. Variables are useful for storing values that may change between environments, for example, different values for test and production environments.

Table of Content

  1. Types of Terraform Variables
  2. Terraform Variables - string, number, bool
  3. Terraform Variables - list, set, map
  4. Terraform Output Variables
  5. How to pass variable as tfvars file as command-line arguments using the -var-file flag?



Pre-requisite

Before we start working with Terraform variables, here are the pre-requisites -

  1. You must install terraform (click here on how to install terraform)
  2. You must have either AWS or Google Cloud account (Click to here for AWS and Google Cloud terraform setup tutorial)

1. Types of Terraform Variables

There are two types of variables in Terraform -

  1. Simple values
  2. Collection Variable

1.1 Simple Values variables

As the name suggests Simple Values variables are which hold only a single value. Here the types of Simple Value variables -

  1. string
  2. number
  3. bool

1.2 Collection Variable

In the collection variable, it consists of -

  1. List
  2. Map
  3. Set


2.Terraform Variables - string, number, bool

Let's take a simple example in which we are going to set up an EC2 instance on AWS.

So to create an EC2 instance we need two things -

  1. provider
  2. resource

Here is the main.tf which we are going to parameterized using terraform variables.

 1provider "aws" {
 2   region     = "eu-central-1"
 3   access_key = "<INSERT_YOUR_ACCESS_KEY>"
 4   secret_key = "<INSERT_YOUR_SECRET_KEY>"
 5}
 6
 7resource "aws_instance" "ec2_example" {
 8   
 9   ami           = "ami-0767046d1677be5a0"
10   instance_type = "t2.micro"
11   
12   tags = {
13           Name = "Terraform EC2"
14   }
15}


2.1 string variable type - We are going parameterized instance_type = "t2.micro"

The first rule to create a parameter in terraform file is by defining variable block

Example -

1variable "instance_type" {
2   description = "Instance type t2.micro"
3   type        = string
4   default     = "t2.micro"
5} 

For defining variable block you need
  1. description : Small or short description about the purpose of the variable
  2. type : What type of variable it is going to be ex - string, bool, number ...
  3. default : What would be the default value of the variable

Let's replace the hardcoded value of instance_type with variable
1 instance_type = var.instance_type

Here is our final terraform file after replacing the hardcoded value of a variable -

 1provider "aws" {
 2   region     = "eu-central-1"
 3   access_key = "<INSERT_YOUR_ACCESS_KEY>"
 4   secret_key = "<INSERT_YOUR_SECRET_KEY>"
 5}
 6
 7resource "aws_instance" "ec2_example" {
 8
 9   ami           = "ami-0767046d1677be5a0"
10   instance_type =  var.instance_type
11
12   tags = {
13           Name = "Terraform EC2"
14   }
15}
16
17variable "instance_type" {
18   description = "Instance type t2.micro"
19   type        = string
20   default     = "t2.micro"
21}

And now you can apply your terraform configuration

1terraform apply 


2.2 number variable type - We are going parameterized instance_count = 2

The next variable type we are going to take is number.

For example, we are going to increase the instance_count of the ec2_instances.

Let's create the variable first -

1variable "instance_count" {
2  description = "EC2 instance count"
3  type        = number
4  default     = 2
5}  

Here is the final terraform file with instance count -

 1provider "aws" {
 2   region     = "eu-central-1"
 3   access_key = "<INSERT_YOUR_ACCESS_KEY>"
 4   secret_key = "<INSERT_YOUR_SECRET_KEY>"
 5}
 6
 7resource "aws_instance" "ec2_example" {
 8
 9   ami           = "ami-0767046d1677be5a0"
10   instance_type =  "t2.micro"
11   count = var.instance_count
12
13   tags = {
14           Name = "Terraform EC2"
15   }
16}
17
18variable "instance_count" {
19  description = "EC2 instance count"
20  type        = number
21  default     = 2
22}


2.3 boolean variable type - We are going parameterized enable_vpn_gateway = false

The next variable type which we are going to discuss is bool.

The bool variable can be used to set true or false values inside your terraform file.

Here is an example to create your bool variable -

1variable "enable_public_ip" {
2  description = "Enable public IP address"
3  type        = bool
4  default     = true
5}

Let's create a complete terraform file with bool variable -

 1provider "aws" {
 2   region     = "eu-central-1"
 3   access_key = "<INSERT_YOUR_ACCESS_KEY>"
 4   secret_key = "<INSERT_YOUR_SECRET_KEY>"
 5}
 6
 7
 8resource "aws_instance" "ec2_example" {
 9
10   ami           = "ami-0767046d1677be5a0"
11   instance_type =  "t2.micro"
12   count = 1
13  associate_public_ip_address = var.enable_public_ip
14
15   tags = {
16           Name = "Terraform EC2"
17   }
18
19}
20
21variable "enable_public_ip" {
22  description = "Enable public IP address"
23  type        = bool
24  default     = true
25}

3. Terraform Variables - list, set, map

When it comes to collection input variables then we are talking about -

  1. List
  2. Map
  3. Set

3.1 List variable type

As the name suggests we are going to define a list that will contain more than one element in it.

Let's define our first List variable -

Here is the list of IAM users

1variable "user_names" {
2  description = "IAM usernames"
3  type        = list(string)
4  default     = ["user1", "user2", "user3s"]
5}

Here is our final terraform file with List variables -

 1provider "aws" {
 2   region     = "eu-central-1"
 3   access_key = "<INSERT_YOUR_ACCESS_KEY>"
 4   secret_key = "<INSERT_YOUR_SECRET_KEY>"
 5}
 6resource "aws_instance" "ec2_example" {
 7
 8   ami           = "ami-0767046d1677be5a0"
 9   instance_type =  "t2.micro"
10   count = 1
11
12   tags = {
13           Name = "Terraform EC2"
14   }
15
16}
17
18resource "aws_iam_user" "example" {
19  count = length(var.user_names)
20  name  = var.user_names[count.index]
21}
22
23variable "user_names" {
24  description = "IAM usernames"
25  type        = list(string)
26  default     = ["user1", "user2", "user3s"]
27}

3.2 Map variable type

Terraform also supports the map variable type where you can define the key-valye pair.

Let's take an example where we need to define project and environment, so we can use the map variable to achieve that.

Here is an example of map variable -

1variable "project_environment" {
2  description = "project name and environment"
3  type        = map(string)
4  default     = {
5    project     = "project-alpha",
6    environment = "dev"
7  }
8}

Let's create a Terraform file

 1provider "aws" {
 2   region     = "eu-central-1"
 3   access_key = "<INSERT_YOUR_ACCESS_KEY>"
 4   secret_key = "<INSERT_YOUR_SECRET_KEY>"
 5}
 6resource "aws_instance" "ec2_example" {
 7
 8   ami           = "ami-0767046d1677be5a0"
 9   instance_type =  "t2.micro"
10
11   tags = var.project_environment
12
13}
14
15
16variable "project_environment" {
17  description = "project name and environment"
18  type        = map(string)
19  default     = {
20    project     = "project-alpha",
21    environment = "dev"
22  }
23}

4. Terraform Output Variables

In Terraform, output variables allow you to easily extract information about the resources that were created by Terraform. They allow you to easily reference the values of resources after Terraform has finished running.

Output variables are defined in the outputs block in the Terraform configuration file. Here's an example of an output variable that references the IP address of an EC2 instance:

1
2output "instance_ip" {
3   value = aws_instance.example.public_ip
4}

In this example, the output variable is named "instance_ip" and its value is set to the public IP of an EC2 instance named "example" that is defined in the Terraform configuration.

What is terraform output command?

You can use the terraform output command to access the value of an output variable:

1 terraform output instance_ip
252.11.222.33

In addition to being able to reference output variables from the command line, you can also reference them in other parts of the Terraform configuration files using output function. For example:

1resource "aws_security_group_rule" "example" {
2   ...
3cidr_blocks = [output.instance_ip]
4}
5 

Output variables are especially useful when you need to pass information about the infrastructure that Terraform has created to other systems or scripts. They also enable you to access the values of resources that are not directly visible in the Terraform state, such as the IP address of an EC2 instance.

It's worth noting that you can also set the output variable to be sensitive, in that case, Terraform will mask the output value when it appears in output, making it more secure.

5. How to pass variable as tfvars file as command-line arguments using the -var-file flag?

In Terraform, you can pass variables from a tfvars file as command-line arguments using the -var-file flag. The -var-file flag allows you to specify a file containing variable values, which will be used when running Terraform commands.

Here is an example of one my terraform project where I have created terraform.tfvars file -

terraform.tfvars file inside the terraform project

Here's an example of how you might use the -var-file flag to pass variables from a tfvars file named terraform.tfvars.

1# You need to supply variable during the terraform init
2terraform init -var-file=terraform.tfvars 
3
4# You need to supply variable during the terraform plan
5terraform plan -var-file=terraform.tfvars
6 
7# You need to supply variable during the terraform apply
8terraform apply -var-file=terraform.tfvars 

What tfvars file should contain?

A typical tfvars file should contain the variables that you want to pass to Terraform. Each variable should be in the form of variable_name = value. For example

1project_id = "gcp-terraform-307119"
2location   = "europe-central2"

But you should also create a variable.tf file also to define the variable type -

variables.tf and terraform.tfvars file containing the variables

 1variable "project_id" {
 2  type        = string
 3  description = "The Project ID"
 4}
 5
 6variable "location" {
 7   description = "Region for project"
 8   default     = "europe-central2"
 9   type        = string
10}

How to pass multiple variables files using -var-file?

You can also specify multiple variable files by using the -var-file flag multiple times on the command line. For example:

1terraform apply -var-file=myvars-1.tfvars -var-file=myvars-2.tfvars

It's worth noting that variables defined in the command line options will have higher priority than the variables defined in the tfvars files.


Read More - Terragrunt -

  1. How to use Terragrunt?

Posts in this Series