slide

Terraform fot d concat()

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

What is it?

Function name: concat(list1, list2, …)

Returns: Takes two or more lists and combines them into a single list. Returns the combined list.

Example:

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

variable "list2" {
  default = ["is","very","long"]
}

# Returns ["My","list","of","stuff","is","very","long"]
output "concat_list" {
  value = "${concat(var.list, var.list2)}"
}

Example file:

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

variable "list_2" {
  default = [6, 7, 42]
}

variable "list_3" {
  default = [false, false, false]
}

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

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

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

output "concat_output" {
  value = "${concat(var.list_1,var.list_2,var.list_3,var.list_4)}"
}

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

#List of different value types is fine
terraform apply

#Cannot combine nested lists and regular lists
terraform apply -var-file="example1.tfvars"

#All nested lists works
terraform apply -var-file="example1.tfvars" -var "list_4=[]"

Why use it?

If you are working with multiple resources, you might get back a list from each one. You can use this function to combine all those lists, and then use something like the distinct function to remove any duplicates. An example that comes to mind is a list of instance sizes available in different Azure regions. I might want some common denominator size, in case there are special sizes in each region.

Lessons Learned

The function will accept lists with values or nested lists. If you want to combine nested lists, you cannot have a flat list as well. There is a flatten function you could use to flatten nested lists before concatenating them. Also, I had assumed that concat was going to be a function for strings and not lists, and I’m not the first one. The function should probably be called concatlist() instead, though I supposed it’s too late for that now.

Coming up next is the contains() function, I can hardly contain my excitement!