0
0
TerraformHow-ToBeginner · 3 min read

How to Use toset Function in Terraform: Simple Guide

In Terraform, the toset function converts a list or tuple into a set, which is an unordered collection of unique values. Use toset() when you want to remove duplicates and treat the data as a set for resource arguments or expressions.
📐

Syntax

The toset function takes one argument, which must be a list or tuple, and returns a set containing the unique elements of that list or tuple.

Syntax:

  • toset(list_or_tuple)

Where:

  • list_or_tuple: A list or tuple of values you want to convert.
  • The result is a set with unique elements, unordered.
terraform
toset(["apple", "banana", "apple"])
Output
set("apple", "banana")
💻

Example

This example shows how to convert a list with duplicate values into a set to ensure uniqueness. The output will display the set with duplicates removed.

terraform
variable "fruits" {
  default = ["apple", "banana", "apple", "orange"]
}

output "unique_fruits" {
  value = toset(var.fruits)
}
Output
unique_fruits = set("apple", "banana", "orange")
⚠️

Common Pitfalls

One common mistake is trying to use toset on a map or a single value, which will cause an error because toset only accepts lists or tuples.

Another pitfall is expecting the set to maintain order; sets are unordered, so the order of elements may change.

terraform
/* Wrong usage: passing a map */
// toset({ key = "value" })  # This will cause an error

/* Correct usage: pass a list */
toset(["value1", "value2"])
📊

Quick Reference

  • Input: List or tuple
  • Output: Set with unique elements
  • Use case: Remove duplicates, pass unique collections
  • Note: Sets are unordered

Key Takeaways

Use toset() to convert lists or tuples into sets with unique values.
Sets do not preserve order; expect elements in any order.
Only pass lists or tuples to toset(), not maps or single values.
Sets are useful for resource arguments that require unique collections.
Remember that toset() removes duplicates automatically.