slide

Terraform fot d chunklist()

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

What is it?

Function name: chunklist(list, size)

Returns: Takes the list and splits it into several lists. Each list will have the number of elements specified in the size property. Any remainder will be in the final list. The function returns the chunked lists as a list value.

Example:

variable "chunklist" {
  default = ["A","list","of","elements"]
}

# Returns [["A","list"],["of","elements"]]
output "chomp" {
  value = "${chunklist(var.chunklist,2)}"
}

Example file:

##############################################
# Function: chunklist
##############################################
##############################################
# Variables
##############################################
variable "chunklist" {
  default = ["one", "two", "three", "four"]
}

variable "chunklist_size" {
  default = 2
}

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

##############################################
# Outputs
##############################################
output "list_output" {
  value = "${var.chunklist}"
}

output "chunklist_output" {
  value = "${chunklist(var.chunklist,var.chunklist_size)}"
}

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

terraform apply -var "chunklist_size=1"

terraform apply -var "chunklist_size=2"

terraform apply -var "chunklist_size=3"

terraform apply -var "chunklist_size=4"

terraform apply -var "chunklist_size=5"

#Empty list
terraform apply -var "chunklist=[]"

Why use it?

There’s a lot of data sources that will return a list. Whether it’s a subnets in VPC, datastores in VMware, network security groups in Azure. Now I’m not sure exactly why I would need to chunk that list into smaller lists, and hope that the data source returned the correct number of items so things chunk evenly. I’m sure there is a use for it, since it exists. If you’re using it, let me know!

Coming up next is cidrhost(), the first of several functions dealing specifically with IP Addressing. For which I am eternally grateful.