How to use the Terraform Toset function | by Jack Roper | January 2024

In this short article, we will take a look at the type conversion function in Terraform, toset() explaining what it can be used for, the difference between it and the tolist() function, along with some helpful examples showing how to use it in a for_each link.

Photo by Sigmund us Remove splash

What is Terraform’s toset function?

toset is a type conversion function used in Terraform to convert its argument to a defined value.

In Terraform, a set is a collection type that represents an unordered collection of unique values. Sets are used to store and manage distinct elements and are commonly used for scenarios where uniqueness and order are not important. The set data type is useful when you want to ensure that each element is unique in the collection.

What is the difference between toset and tolist?

  • toset() converts a value into a set, ensuring uniqueness and unordered nature.
  • tolist() converts a value to a list, preserving the order of the elements.

In Terraform, a list is a type of collection that represents an ordered sequence of elements. Lists are used to store and manage a series of values, and the order in which elements are defined in the list is maintained. Elements in a list can be of various types, such as strings, numbers, or other complex data structures.

How to use Terraform toset – example

The syntax is toset(value)where value is the input value you want to convert to a set. In the example below we have a list that we converted into a set.

variable "my_list" {
type = list(string)
default = ("luke", "yoda", "darth")

locals {
my_set = toset(var.my_list)

output "set_output" {
value = local.my_set

The output would show:


set_output = toset((

You can also use the Terraform console to try out Terraform functions. For example, the simple test providing the values ​​directly to the toset()The function in the terraform console shows the same output:

Leave a Comment