Sorting Lists in Terraform: A Practical Guide

Updated: February 4, 2024 By: Guest Contributor Post a comment


In this comprehensive guide, we will delve into the nuanced world of sorting lists in Terraform. Terraform, a potent tool in the realm of Infrastructure as Code (IaC), offers us the flexibility to define, provision, and manage infrastructure using simple, declarative configuration files. Among its myriad features, the ability to manipulate and sort lists stands out for its utility in organizing resources and configurations dynamically.

Understanding how to effectively sort lists in Terraform can significantly enhance your infrastructure configurations, ensuring they are both efficient and easily maintainable. Throughout this guide, we will explore various methods to achieve effective list sorting within your Terraform projects.

Understanding Lists in Terraform

Before diving into the sorting techniques, let’s briefly recollect what lists are in the context of Terraform. A list is a collection of values that are ordered and indexable. Lists in Terraform can contain elements of the same type, providing a structured way to manage groups of related resources.

For example, a simple list of strings in Terraform might look like this:

variable "my_list" { 
  type    = list(string) 
  default = ["apple", "banana", "cherry"] 

This variability and the need to manipulate these lists bring us to our main focus: sorting.

Basic Sorting with the sort Function

The simplest way to sort a list in Terraform is by using the built-in sort function. The sort function sorts a list of strings in ascending lexicographical order. Here is how you can use it:

sorted_list = sort(var.my_list) 

This function will sort our example list from earlier into ["apple", "banana", "cherry"], which, given our initial ordering, is not a change. But, if our list were ["cherry", "banana", "apple"], sorting it would rearrange it as shown above.

Advanced Sorting Techniques

Sorting becomes more nuanced when dealing with lists that are not as straightforward. Suppose you have a list of maps, where each map represents a cloud resource with different attributes, and you wish to sort this list based on one of those attributes. Terraform doesn’t have a built-in function for such complex sorts, but we can leverage the sort function in combination with other Terraform functions to accomplish our goal.

For instance, to sort a list of maps by the name attribute:

variable "cloud_resources" { 
  type    = list(object({ 
    name = string 
    type = string 
  default = [ 
      name = "server-a", 
      type = "compute" 
      name = "database-b", 
      type = "storage" 
      name = "cache-c", 
      type = "memory" 
sorted_resources = sort([for r in var.cloud_resources:]) 

In the above code snippet, we first use a for expression to extract the name attribute from each map in our list. We then sort this list of names and, if needed, can use it to reorder the original list of maps.

Custom Sorting Logic

For situations where the built-in sort doesn’t suffice, e.g., when needing a descending order or sorting numerical values, Terraform’s language allows for constructing loops and conditional expressions that can form the basis of a custom sort function. This process tends to be more complex and requires careful implementation to ensure efficiency and accuracy.

As an example, let’s consider sorting a list of numbers in descending order. Although Terraform does not provide a direct method for this, we can employ a creative approach using a combination of Terraform functions:

variable "numbers_list" { 
  type    = list(number) 
  default = [ 5, 1, 3, 4, 2 ] 
desc_sorted_numbers = reverse(sort(var.numbers_list)) 

Here, we first sort the list in ascending order and then reverse it to achieve a descending order. This approach highlights the flexibility of Terraform in crafting solutions to fit your needs.

Best Practices for Sorting in Terraform

When sorting lists in Terraform, considering some best practices can ensure that your solutions are both effective and maintainable:

  • Understand the data: Before sorting, ensure you fully understand the structure and attributes of the data you’re working with. This understanding is crucial for devising an effective sorting strategy.
  • Keep performance in mind: While Terraform scripts can be powerful, overly complex operations might impact the performance of your infrastructure deployments. Strive for simplicity and efficiency in your solutions.
  • Document your logic: Sorting logic, especially custom implementations, can be complex. Proper documentation ensures that future maintainers of your Terraform configurations can quickly grasp and modify your sorting approach if necessary.

Final Words

Sorting lists in Terraform, whether simple strings or complex nested structures, is an essential skill in managing dynamically configured resources efficiently. By understanding the built-in functions and exploring custom logic when necessary, you can significantly enhance your Terraform deployments, ensuring they are both orderly and easily maintainable.

By adhering to the principles and techniques discussed in this guide, you can master the art of sorting lists in Terraform, paving the way for more organized, efficient, and effective infrastructure management. Happy terraforming!