Member-only story
Terraform Variables (Part-2)

In the following article, we explore the utilization of variables within Terraform, a tool that employs HashiCorp Configuration Language (HCL) to define infrastructure setups. The approach in Terraform is declarative, where multiple code blocks are defined to establish a desired infrastructure arrangement.
Before delving into the diverse variable types, it’s constructive to conceptualize the entire Terraform configuration as a unified function. Concerning variables, they operate akin to functions, taking on roles similar to function arguments, return values, and local variables. These roles align with input variables, output variables, and local variables within the Terraform context.
The topics we’ll address encompass:
- Local variables
- Input variables
- Incorporating environment variables
- Output variables
- Constraints
Types of Variables
Local Variables
- Local variables are established within the locals block, constituting a collection of key-value associations applicable within the configuration. These values might either be explicitly defined or linked to other variables or resources.
- Accessible solely within the module or configuration of their declaration, local variables facilitate organization and reusability. To illustrate, let’s consider the creation of an EC2 instance configuration employing local variables. This configuration snippet can be added to a file named main.tf.
locals {
ami = "ami-0f37eb6382b3g7c54"
type = "t2.micro"
tags = {
Name = "terraform"
Env = "UAT"
}
subnet = "subnet-43h2163a"
nic = aws_network_interface.my_nic.id
}
resource "aws_instance" "myvm" {
ami = local.ami
instance_type = local.type
tags = local.tags
network_interface {
network_interface_id = aws_network_interface.my_nic.id
device_index = 0
}
}
resource "aws_network_interface" "my_nic" {
description = "My NIC"
subnet_id = var.subnet
tags = {
Name = "My NIC"
}
}
- Within this illustration, all the local variables find their declaration within the locals block. These variables encompass the AMI ID…