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.
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)}"
}
##############################################
# 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
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.
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.
Resourcely Guardrails and Blueprints
November 15, 2024
Deploying Azure Landing Zones with Terraform
November 12, 2024
October 18, 2024
What's New in the AzureRM Provider Version 4?
August 27, 2024