Member-only story

Terraform Variables (Part-2)

Kamalesh D
7 min readAug 11, 2023

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:

  1. Local variables
  2. Input variables
  3. Incorporating environment variables
  4. Output variables
  5. 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…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Kamalesh D
Kamalesh D

Written by Kamalesh D

DevOps and Cloud Enthusiast | Cyber Security | DevSecOps Engineer@FordMotors | https://dev.to/kamaleshseervi

No responses yet

Write a response