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.
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)}"
}
##############################################
# 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=[]"
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.
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!
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