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.
- 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 can have various type such as string, number, boolean, list, map etc.
- Variables can be set in the command line when running Terraform commands using the
-var
flag. - Variables can also be set using a separate file, called a variable file, using the
-var-file
flag. - Variables can be accessed in Terraform configuration files using the var function, for example
var.example_variable
- Variables are useful for storing values that may change between environments, for example, different values for test and production environments.
Table of Content
- Types of Terraform Variables
- Terraform Variables - string, number, bool
- Terraform Variables - list, set, map
- Terraform Output Variables
- 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 -
- You must install terraform (click here on how to install terraform)
- 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 -
- Simple values
- 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 -
- string
- number
- bool
1.2 Collection Variable
In the collection variable, it consists of -
- List
- Map
- 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 -
- provider
- 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
- description : Small or short description about the purpose of the variable
- type : What type of variable it is going to be ex -
string
,bool
,number
... - 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 -
- List
- Map
- 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 -
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 -
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 -
Posts in this Series
- Securing Sensitive Data in Terraform
- Boost Your AWS Security with Terraform : A Step-by-Step Guide
- How to Load Input Data from a File in Terraform?
- Can Terraform be used to provision on-premises infrastructure?
- Fixing the Terraform Error creating IAM Role. MalformedPolicyDocument Has prohibited field Resource
- In terraform how to handle null value with default value?
- Terraform use module output variables as inputs for another module?
- How to Reference a Resource Created by a Terraform Module?
- Understanding Terraform Escape Sequences
- How to fix private-dns-enabled cannot be set because there is already a conflicting DNS domain?
- Use Terraform to manage AWS IAM Policies, Roles and Users
- How to split Your Terraform main.tf File into Multiple Files
- How to use Terraform variable within variable
- Mastering the Terraform Lookup Function for Dynamic Keys
- Copy files to EC2 and S3 bucket using Terraform
- Troubleshooting Error creating EC2 Subnet InvalidSubnet Range The CIDR is Invalid
- Troubleshooting InvalidParameter Security group and subnet belong to different networks
- Managing strings in Terraform: A comprehensive guide
- How to use terraform depends_on meta argument?
- What is user_data in Terraform?
- Why you should not store terraform state file(.tfstate) inside Git Repository?
- How to import existing resource using terraform import comand?
- Terraform - A detailed guide on setting up ALB(Application Load Balancer) and SSL?
- Testing Infrastructure as Code with Terraform?
- How to remove a resource from Terraform state?
- What is Terraform null Resource?
- In terraform how to skip creation of resource if the resource already exist?
- How to setup Virtual machine on Google Cloud Platform
- How to use Terraform locals?
- Terraform Guide - Docker Containers & AWS ECR(elastic container registry)?
- How to generate SSH key in Terraform using tls_private_key?
- How to fix-Terraform Error acquiring the state lock ConditionalCheckFiledException?
- Terraform Template - A complete guide?
- How to use Terragrunt?
- Terraform and AWS Multi account Setup?
- Terraform and AWS credentials handling?
- How to fix-error configuring S3 Backend no valid credential sources for S3 Backend found?
- Terraform state locking using DynamoDB (aws_dynamodb_table)?
- Managing Terraform states?
- Securing AWS secrets using HashiCorp Vault with Terraform?
- How to use Workspaces in Terraform?
- How to run specific terraform resource, module, target?
- How Terraform modules works?
- Secure AWS EC2s & GCP VMs with Terraform SSH Keys!
- What is terraform provisioner?
- Is terraform destroy needed before terraform apply?
- How to fix terraform error Your query returned no results. Please change your search criteria and try again?
- How to use Terraform Data sources?
- How to use Terraform resource meta arguments?
- How to use Terraform Dynamic blocks?
- Terraform - How to nuke AWS resources and save additional AWS infrastructure cost?
- Understanding terraform count, for_each and for loop?
- How to use Terraform output values?
- How to fix error configuring Terraform AWS Provider error validating provider credentials error calling sts GetCallerIdentity SignatureDoesNotMatch?
- How to fix Invalid function argument on line in provider credentials file google Invalid value for path parameter no file exists
- How to fix error value for undeclared variable a variable named was assigned on the command line?
- What is variable.tf and terraform.tfvars?
- How to use Terraform Variables - Locals,Input,Output
- Terraform create EC2 Instance on AWS
- How to fix Error creating service account googleapi Error 403 Identity and Access Management (IAM) API has not been used in project before or it is disabled
- Install terraform on Ubuntu 20.04, CentOS 8, MacOS, Windows 10, Fedora 33, Red hat 8 and Solaris 11