Pass a List Variable in Terraform: A Comprehensive Guide

Learn Terraform list variables with our comprehensive guide! Pass, use, and troubleshoot list variables effectively. Start optimizing today!

Kashyap Merai / / terraform  · 5 min read

Learn Terraform list variables with our comprehensive guide! Pass, use, and troubleshoot list variables effectively. Start optimizing today!

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:

Complex types such as collections:

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

Free DevOps Learning Board for Absolute Beginners

11 core modules, curated content, and clear action steps - all in one interactive Notion board.

DevOps-Notion-Training-Board

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.

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:

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:

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:

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:

# terraform.tfvars
availability_zones = ["us-west-1a", "us-west-1b", "us-west-1c"]

Pass a List Variable in Terraform from the Command Line

terraform apply -var 'instance_types=["t2.micro", "t2.small", "t2.medium"]'
DevOps-Notion-Training-Board

Kickstart Your DevOps Career

Get the free Notion training board that shows you exactly what to learn, in what order, with zero guesswork.

Pass a List Variable in Terraform: Practical Example

Pass a List Variable in Terraform with Instance Type

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

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

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)
}
CTA image for DevOps-Notion-Training-Board

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:

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:

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:

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"
}

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

DevOps-Notion-Training-Board

Kickstart Your DevOps Career

Get the free Notion training board that shows you exactly what to learn, in what order, with zero guesswork.

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 8 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.

Related Posts