Terraform

How to use Terraform Variables

Hello. In this tutorial, we will explain the usage of variables in Terraform scripting language.

1. Introduction

Terraform is an open-source tool developed by HashiCorp for building, changing, and versioning the infrastructure safely and efficiently. It is used to manage the infrastructure of the popular cloud service providers and custom in-house solutions. It helps manage both low-level (Compute, Storage, Networking, etc.) and high-level components (such as SaaS, DNS, etc.) Terraform deployment automation is divided into different sections i.e.:

  • IaaC – IaaC is popularly known as the Infrastructure as a Code wherein the infrastructure is described using a high-level configuration syntax. This allows a blueprint of the infrastructure which can be deployed, versioned, and shared for re-use
  • Execution Plans – Terraform has a planning step where it generates an execution plan. The execution plan tells the administrator what Terraform will do once applied and helps to avoid any surprises when it creates the infrastructure
  • Resource Graph – Terraform builds a graph of all the resources and parallelizes the creation and modification of non-dependent resources. This offers insights into learning the dependencies in their infrastructure
  • Change Automation – Terraform allows to apply of complex changesets to the infrastructure with minimal human intervention

1.1 Configuration language

Terraform has its configuration language designed to meet the infrastructure automation requirements. The main purpose of this language is to declare resources and a group of resources (gathered into a module) represents a larger unit of configuration. Language syntax consists of a few elements i.e. – Blocks, Arguments, and Expressions.

  • Blocks – Containers for other contents and represents the object configuration
  • Arguments – Assign a value to the name and appear within the blocks
  • Expressions – Represents a single value, referenced value, or combination of other values

1.2 Steps

To create the infrastructure via the Terraform scripts following commands need to be executed in a sequence. However, details and actions may differ between workflows.

  • terraform init – Initializing the new or existing terraform configuration
  • terraform plan – Generate the execution plan from the resources specified in the file
  • terraform apply – Create the infrastructure from the resources specified in the file
  • terraform destroy – Destroy the created infrastructure
terraform variables - workflow
Fig. 1: Terraform workflow

2. How to use Terraform variables

In terraform, variables usage make the configuration more dynamic. In this article, we will cover the usage of input and output variables. Let us dive into and briefly understand the input and output variables along with their usage.

2.1 Input variables

Input variables in terraform scripting language are used to specify variables at the runtime to set up the infrastructure deployment in the cloud. The variables are defined in the main terraform file but as a recommended practice these variables are defined in a separate file known as variables.tf to provide better readability and organization of things. A variable in the file is defined inside the variable block with a label and consists of three optional arguments i.e.

  • description: Define the purpose of the variable
  • type: Specify the datatype such as primitive (string, number, bool) and complex (list, map, object)
  • default: If present, value is considered to be optional and if no value is set the default value will be used

Every label name for the variable should be unique in the configuration file and are accessed in the var.variable_name format. A sample variable file from the aws environment looks like –

variables.tf

variable "aws_access_key" {
  type        = string
  description = "cli user access key"
  default     = "YOUR_AWS_ACCESS_KEY"
}
variable "aws_secret_key" {
  type        = string
  description = "cli user secret key"
  default     = "YOUR_AWS_SECRET_KEY"
}
variable "region" {
  type        = string
  description = "ec2 region"
  default     = "ap-south-1"
}
variable "tags" {
  type        = map(string)
  description = "mapping of tags to assign to the ec2 instance"
  default = {
    environment = "development"
    terraform   = "true"
    company     = "ducat"
    batch       = "devops"
  }
}

2.2. How to use input variables?

Once the variable file is created in section2.1 let us make an implementation file that will refer to the variables from the same file. The variables are referenced using the var keyword in the implementation file.

ec2.tf

resource "aws_security_group" "ec2-sg" {
  name        = "ec2-sg"
  description = "security group for ec2"
  vpc_id      = "vpc-66d81b0d"
  ingress = [
    {
      # ssh port allowed from any ip
      description      = "ssh"
      from_port        = 22
      to_port          = 22
      protocol         = "tcp"
      cidr_blocks      = ["0.0.0.0/0"]
      ipv6_cidr_blocks = null
      prefix_list_ids  = null
      security_groups  = null
      self             = null
    }
  ]
  egress = [
    {
      description      = "all-open"
      from_port        = 0
      to_port          = 0
      protocol         = "-1"
      cidr_blocks      = ["0.0.0.0/0"]
      ipv6_cidr_blocks = null
      prefix_list_ids  = null
      security_groups  = null
      self             = null
    }
  ]
  tags = {
    "name"      = "terraform-sg"
    "terraform" = "true"
  }
}

resource "aws_instance" "terraforminstance" {
  ami               = "ami-0a23ccb2cdd9286bb" # remember to check for free-tier ami id before runnning the script to avoid unwanted money
  availability_zone = "ap-south-1a"
  instance_type     = "t2.micro"
  key_name          = var.key_name
  count             = 1
  security_groups   = ["${aws_security_group.ec2-sg.id}"]
  subnet_id         = "subnet-c98f67a2"
  ebs_block_device {
    device_name           = "/dev/xvda"
    volume_size           = 8
    volume_type           = "gp2"
    delete_on_termination = true
  }
  tags = var.tags
}

2.3 Output variables

Output variables in terraform scripting language allow developers to define variables in the configuration file that we want to share with other resources or users. For eg. Display the public IP address or the EC2 instance id/name etc. An output variable is defined inside the output block with a label. Every label name should be unique in the configuration file. Here is a sample output file from the aws environment which will return the output values for the created resource.

outputs.tf

output "id" {
  description = "instance-id"
  value       = aws_instance.terraforminstance[0].id
}
output "arn" {
  description = "instance-arn"
  value       = aws_instance.terraforminstance[0].arn
}
output "instance_state" {
  description = "instance-state"
  value       = aws_instance.terraforminstance[0].instance_state
}
output "keyname" {
  description = "keyname"
  value       = aws_instance.terraforminstance[0].key_name
}
output "public_ip" {
  description = "public-ip"
  value       = aws_instance.terraforminstance[0].public_ip
}

Remember to create the provider file before you go ahead and deploy this sample code in the aws environment. I am skipping this for brevity. In case you’re interested to see how a provider file looks please go through this tutorial at the javacodegeeks website.

3. Code run & demo

Navigate to the project directory containing the above scripts and open the terminal. Execute the below commands in the respective order within the directory.

Commands

-- step1: initializing the new or existing terraform configuration --
terraform init

-- step2: generating the execution plan --
terraform plan

-- step3: building the infrastructure --
-- auto-approve flag skips interactive approval of the plan before applying
terraform apply --auto-approve

-- step4: destroying the infrastructure --
-- auto-approve flag skips interactive approval of the plan before applying
terraform destroy --auto-approve

Once these scripts are executed successfully head over to the aws console to confirm that the required resources such as security group and ec2 instance are created on the ec2 dashboard.

terraform variables - instance
Fig. 2: Created instance

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

4. Summary

In this tutorial, we learned an introduction to Terraform and understood the usage of input and output variables in the implementation file while creating the infrastructure in the real environment. You can download the source code from the Downloads section.

5. Download the Project

This was a tutorial to learn the usage of variables in the terraform.

Download
You can download the full source code of this example here: How to use Terraform Variables

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button