Pass a List Variable in Terraform: A Comprehensive Guide

Estimated reading time: 6 minutes

Last updated on November 8th, 2024 at 03:40 pm

Terraform Variables

What are the Variables in Terraform?

Terraform variables allow you to customize and reuse your infrastructure configuration without hardcoding the values. Using the Terraform variables you can define the flexible and dynamic configuration for your infrastructure.

Importance of Using Variables

Terraform Variables can make your infrastructure configuration modular, reusable, and maintainable.

You can define the values for the variable once and take reference in your infrastructure configuration file, which allows you to update easily without of chance of error.

Difference Types of Variables in Terraform

Terraform offers various types of variables:

  • string
  • number
  • bool

Complex types such as collections:

  • list(<TYPE>)
  • set(<TYPE>)
  • map(<TYPE>)
  • object({<ATTR NAME> = <TYPE>, ... })
  • tuple([<TYPE>, ...])

Choosing the appropriate type is important and helps you manage your infrastructure configuration effectively.

Fast-Track Your DevOps Career 🚀

Stay ahead of the curve with the latest industry insights. Get weekly tips & propel your skills to the next level.

Subscribe Now!

Understanding List Variables in Terraform

What is a List Variable?

A List variable in Terraform is a collection of values.

If you come from a programming background you can consider that as an array for storing multiple values in a single variable.

List variables are important for managing the collection of the related values.

The use case for strong the multiple values in a single List variable is, to iterate over multiple values such as multiple instances or security groups or ACL rules.

Syntax and Structure of List Variable

You can define the list variable in Terraform using the square brackets []. Each item in the list is separated by a comma.

HCL
variable "sample_list" {
  type    = list(string)
  default = ["item1", "item2", "item3"]
}

How to Define List Variables in Terraform

You can define the list variable by specifying the type and the default values if you need:

HCL
variable "instance_types" {
  type    = list(string)
  default = ["t2.micro", "t2.small", "t2.medium"]
}
Example: Define a List Variable

Let’s define a list variable to store multiple availability zones:

HCL
variable "availability_zones" {
  type    = list(string)
  default = ["us-west-1a", "us-west-1b", "us-west-1c"]
}

Common Use Cases for List Variable

List variables are mostly used for:

  • Define multiple AWS instance types
  • Define the CIDR blocks or IP address
  • Manage multiple resource configurations

Pass a List Variable in Terraform

Using CLI to Pass a List Variable in Terraform

You can pass a list variable in Terraform by using the CLI with the -var flag:

HCL
terraform apply -var 'availability_zones=["us-west-1a", "us-west-1b", "us-west-1c"]'
Pass a List Variable in Terraform via Configuration File

You can also pass a list variable in Terraform with the .tfvars files:

Bash
# terraform.tfvars
availability_zones = ["us-west-1a", "us-west-1b", "us-west-1c"]
Pass a List Variable in Terraform from the Command Line
Bash
terraform apply -var 'instance_types=["t2.micro", "t2.small", "t2.medium"]'

Pass a List Variable in Terraform: Practical Example

Pass a List Variable in Terraform with Instance Type
HCL
variable "instance_types" {
  type    = list(string)
  default = ["t2.micro", "t2.small", "t2.medium"]
}

resource "aws_instance" "example" {
  count         = length(var.instance_types)
  instance_type = element(var.instance_types, count.index)
  ami           = "ami-0c55b156cbfafef20"
}
Pass a List Variable in Terraform for Security Groups
HCL
variable "allowed_ports" {
  type    = list(number)
  default = [80, 443]
}

resource "aws_security_group" "example" {
  name = "sg_groups"

  dynamic "ingress" {
    for_each = var.allowed_ports
    content {
      from_port   = ingress.value
      to_port     = ingress.value
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }
}
Pass a List Variable in Terraform for Multiple Resource Configuration
HCL
variable "availability_zones" {
  type    = list(string)
  default = ["us-west-1a", "us-west-1b", "us-west-1c"]
}

resource "aws_subnet" "subnet" {
  count             = length(var.availability_zones)
  vpc_id            = "vpc-95434234"
  cidr_block        = "10.0.${count.index}.0/24"
  availability_zone = element(var.availability_zones, count.index)
}

Pass a List Variable in Terraform: Advanced

Nesting List Variables

You can define the variable with the nested list to create the complex data structure:

HCL
variable "nested_list" {
  type = list(list(string))
  default = [["us-west-1a", "us-west-1b"], ["us-east-1a", "us-east-1b"]]
}
Combine List Variables with Other Variable Types

You can combine the lists with maps for more structure and complex data structure:

HCL
variable "instance_configs" {
  type = list(object({
    instance_type = string
    ami           = string
  }))
  default = [
    { instance_type = "t2.micro", ami = "ami-0c65b159cbs2d21f0" },
    { instance_type = "t2.small", ami = "ami-0cf5bas5dcbfafe1f0" }
  ]
}
Use Conditional Logic with List Variables

You can use the conditional logic with your list variables:

HCL
variable "instance_types" {
  type    = list(string)
  default = ["t2.micro", "t2.small"]
}

locals {
  selected_instance_types = length(var.instance_types) > 2 ? var.instance_types : ["t2.micro"]
}

resource "aws_instance" "example" {
  count         = length(local.selected_instance_types)
  instance_type = element(local.selected_instance_types, count.index)
  ami           = "ami-0c66b769cafafg1r5"
}

DevOps Efficiency Hacks in Your Inbox! 📩

Stop wasting time searching. Get weekly tips & tutorials to streamline your DevOps workflow.

Subscribe Now!

Pass a List Variable in Terraform: Troubleshoot

The most common error when passing a list variable in Terraform includes a typo error or incorrect list syntax. Define the variable list correctly and pass the matching type with it.

Debugging Tips

Terraform Validate vs Plan: Understanding the Key Differences

Best Practices: Pass a List Variable
  • Always specify the type of the variables.
  • Clearly define the purpose of the variable and its usage with the documentation.
  • Use meaningful variable names for code readability.

Terraform Comment Block: A Comprehensive Guide

Conclusion

In this article, we learned:

  • The basics of variables in Terraform and list variables.
  • How to pass a list variable in Terraform
  • Practical example and advanced method for using list variable.
  • Troubleshooting common issues.

At last, the best way to master Terraform is through practicals. Experiment with the types and configurations of the different variables to understand how to utilize and improve your infrastructure management.

Kashyap Merai

Kashyap Merai

Kashyap Merai, a Certified Solution Architect and Public Cloud Specialist with over 7 years in IT. He helped startups in Real Estate, Media Streaming, and On-Demand industries launch successful public cloud projects.

Passionate about Space, Science, and Computers, He also mentors aspiring cloud engineers, shaping the industry's future.

Connect with him on LinkedIn to stay updated on cloud innovations.