slide

Terraform fot d zipmap()

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

What is it?

Function name: zipmap(list, list)

Returns: Takes two lists of equal length and returns a map with the first list as keys and the second list as values.

Example:

# Returns { "k1":"v1" "k2":"v2" }
output "zipmap_output" {
  value = "${zipmap(list("k1","k2"), list("v1","v2"))}"
}

Example file:

##############################################
# Function: zipmap
##############################################
##############################################
# Variables
##############################################
variable "list_1" {
  type = "list"

  default = [["n1v1","n1v2"],["n2v1","n2v2"]]
}

variable "map_1" {
  type = "map"

  default = {
    "k1" = "v1"
    "k2" = "v2"
  }
}

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

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

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

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

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

output "1_standard_list" {
  value = "${zipmap(list("k1","k2","k3"),list("v1","v2","v3"))}"
}

output "2_empty_values" {
  value = "${zipmap(var.list_3, var.list_2)}"
}

output "3_nest_list_values" {
  value = "${zipmap(list("k1","k2"), var.list_1)}"
}

output "4_nest_map_values" {
  value = "${zipmap(list("k1","k2"), list(var.map_1,var.map_1))}"
}

output "5_nest_mixed_lengths" {
  value = "${zipmap(list("k1","k2"), list(var.list_4,var.list_3))}"
}

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

#All examples are in variables
terraform apply

Why use it?

You’ve got a list and you want a map. Or more likely, you have strings that represent lists and maps from the output of a module. Since modules currently only support a string output, you might use the split function to get the list of keys and list of values. Then use zipmap to create the map from that. You could also dynamically create maps from separate data sources that return lists.

Lessons Learned

The keys and values lists have to be the same length. The function will allow both nested lists and nested maps for the values, but only a list of strings for the keys. Not a surprise there. There can be a different number of elements in the nested lists. You cannot mix and match maps, lists, and strings for the values.

Coming up next is no function! That’s it folks. My next post will be a wrap up of this whole FotD series.