Terraform – FotD – compact()

This is part of an ongoing series of posts documenting the built-in interpolation functions in Terraform. For more information, check out the beginning post. In this post I am going to cover the compact() function. The example file is on GitHub here.

What is it?

Function name: compact(list)

Returns: Takes a list and removes any empty string values in the list.

Example:

variable "list" {
  default = ["My","list","","of","","stuff"]
}

# Returns ["My","list","of","stuff"]
output "compact_list" {
  value = "${compact(var.list)}"
}

Example file:

##############################################
# Function: compact
##############################################
##############################################
# Variables
##############################################
variable "list" {
  default = ["", "so", "long", "", "and", " ", "thanks", ""]
}

variable "empty_list" {
  default = []
}

variable "empty_string_list" {
  default = ["", "", ""]
}

variable "bool_list" {
  default = [false, "zaphod", "", true, 0, 1]
}

##############################################
# Resources
##############################################

##############################################
# Outputs
##############################################

#Test a standard list
output "compact_list" {
  value = "${compact(var.list)}"
}

#Test what it will do with an empty list
output "compact_empty_list" {
  value = "${compact(var.empty_list)}"
}

#Test what will happen with a list full of empty strings
output "compact_empty_string_list" {
  value = "${compact(var.empty_string_list)}"
}

#Test how the function interprets boolean values
output "compact_bool_list" {
  value = "${compact(var.bool_list)}"
}

Run the following from the compact folder to get example output for a number of different cases:

#All examples are in variables
terraform apply

Why use it?

One thing I learned early on, is to sanitize your input. Assume that any module or user is going to give you crappy input, so try and clean it up. Compact could be used with other functions to clean up list data, making sure there are no empty values. You might also run something like distinct() to remove duplicate values.

Lessons Learned

The function will only accept a flat list, no nested lists allowed. If you suspect you’re going to get a nested list, use the flatten function first to un-nest those lists. As usual, boolean false evaluates to 0. Whitespace does not count as an empty string, so a list with the string ” “, will not remove that element. The function is fine with an empty list or a list of just empty strings.

Coming up next is the concat() function.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.