slide

Terraform fot d list()

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

What is it?

Function name: list(value, value, value,…)

Returns: Takes one or more values of string, list, or map and returns a list containing those values as elements.

Example:

variable "string" {
  type = "string"

  default = "Four"
}

# Returns ["Four"]
output "list_output" {
  value = "${list(var.string)}"
}

Example file:

##############################################
# Function: list
##############################################
##############################################
# Variables
##############################################
variable "value_1" {
  default = "Ford"
}

variable "value_2" {
  default = "Prefect"
}

variable "value_3" {
  default = "Arthur"
}

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

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

output "1_basic_list_output" {
  value = "${list(var.value_1,var.value_2,var.value_3)}"
}

output "2_nested_list_output" {
  value = "${list(list(var.value_1),list(var.value_2,var.value_3))}"
}

output "3_map_list_output" {
  value = "${list(map("life","42","universe","6"),map("everything","7"))}"
}

output "4_empty_list" {
  value = "${list()}"
}

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

#All examples are in variables
terraform apply

Why use it?

If you need to pack stuff up as a list to pass to another resource or module, then this is the way to do it. This one is pretty straightforward. I’ve also used this function in a bunch of the other examples to test a list against another function.

Lessons Learned

One thing I learned, which is missing from the documentation, is that this function will happily accept a bunch of string, list, or map values and return a list containing them. What it will not do is allow you to mix value types in the list. If you try something like list("a",list("b")) then it will throw an error saying that element one (1) is a list and it was expecting a string. No big deal, but something to keep in mind. Otherwise the function works as advertised.

Coming up next is the log() function.