slide

Terraform fot d flatten()

Ned Bellavance
2 min read

Cover

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 flatten() function. The example file is on GitHub here.

What is it?

Function name: flatten(list)

Returns: Takes a list with nested values and returns a flat list with all values removing nested lists.

Example:

variable "flatten" {
  default = ["one",["two",3]]
}

# Returns ["one","two",3]
output "flatten_output" {
  value = "${flatten(var.flatten)}"
}

Example file:

##############################################
# Function: flatten
##############################################
##############################################
# Variables
##############################################
variable "list_1" {
  default = []
}

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

variable "list_3" {
  default = [0, [1, 2, 3], [4, 5, 6], [7, 8], 9, 0]
}

variable "list_4" {
  default = ["So", "Long", "and", "Thanks"]
}

variable "list_5" {
  default = [[[1, 2, 3], [4, 5, 6]], [[7, 8], [9, 10]], 11, 12]
}

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

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

output "1_flatten_empty_list" {
  value = "${flatten(var.list_1)}"
}

output "2_flatten_list_of_empty_lists" {
  value = "${flatten(var.list_2)}"
}

output "3_flatten_mixed_list" {
  value = "${flatten(var.list_3)}"
}

output "4_flatten_flat_list" {
  value = "${flatten(var.list_4)}"
}

output "5_flatten_double_nested_list" {
  value = "${flatten(var.list_5)}"
}

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

#All examples are in variables
terraform apply

Why use it?

Depending on the data source, or resource, you might get a messy nested list back. Say you have a list of security groups, and each security group has rules, and each rule has a set of allowed ports. If you want to know all the allowed ports in all the rules, then you could flatten the list of a list of a list to get that. Fun times really.

Lessons Learned

I would have thought that the function would take multiple lists and flatten them all into one. But that is the job of the concat function. The concat function, if you’ll remember, doesn’t handle nested lists and flat lists in the same function call. So you may need to use flatten first before concatenating the lists together. And you might also use distinct and chomp to clean up your data. Basically, there’s a lot of good list functions.

Coming up next is the format() function.