0
0
TerraformHow-ToBeginner · 3 min read

How to Use tolist Function in Terraform: Simple Guide

In Terraform, the tolist function converts a given value into a list type. It is useful when you want to ensure a value is treated as a list, especially when working with dynamic or mixed types.
📐

Syntax

The tolist function takes one argument, which is the value you want to convert to a list. It returns a list version of that value.

  • tolist(value): Converts value to a list.
  • If value is already a list, it returns it unchanged.
  • If value is a tuple or set, it converts it to a list.
terraform
tolist(value)
💻

Example

This example shows how to use tolist to convert a set and a tuple into a list. It also shows that if the value is already a list, it stays the same.

terraform
variable "example_set" {
  default = toset(["apple", "banana", "cherry"])
}

variable "example_tuple" {
  default = ["dog", "cat", "bird"]
}

output "list_from_set" {
  value = tolist(var.example_set)
}

output "list_from_tuple" {
  value = tolist(var.example_tuple)
}

output "list_from_list" {
  value = tolist(["red", "green", "blue"])
}
Output
list_from_set = ["apple", "banana", "cherry"] list_from_tuple = ["dog", "cat", "bird"] list_from_list = ["red", "green", "blue"]
⚠️

Common Pitfalls

One common mistake is trying to use tolist on a map or string, which will cause an error because tolist expects a tuple, set, or list-like value.

Also, using tolist on a single scalar value (like a string or number) will fail because it cannot convert it into a list automatically.

terraform
/* Wrong usage: trying to convert a map to list */
variable "example_map" {
  default = { key1 = "value1", key2 = "value2" }
}

output "wrong_list" {
  value = tolist(var.example_map) # This will cause an error
}

/* Correct approach: convert map values to list explicitly */
output "correct_list" {
  value = tolist(values(var.example_map))
}
📊

Quick Reference

  • Input types: tuple, set, or list
  • Output type: list
  • Use case: normalize input to list for consistent processing
  • Errors: occurs if input is map, string, or scalar

Key Takeaways

Use tolist to convert tuples or sets into lists for consistent data handling.
Applying tolist on maps or single values causes errors; convert maps with values() first.
If the input is already a list, tolist returns it unchanged.
Always check the input type before using tolist to avoid runtime errors.