Terraform – FotD – keys()

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

What is it?

Function name: keys(map)

Returns: Takes a map and returns the keys of that map in a list that has been lexically sorted.

Example:

variable "map" {
  type = "map"

  default = {
    "one" = "1"
    "two" = "2"
  }
}

# Returns ["one","two"]
output "key_output" {
  value = "${keys(var.map)}"
}

Example file:

##############################################
# Function: keys
##############################################
##############################################
# Variables
##############################################
variable "map_value" {
  type = "map"

  default = {
    "life"       = "42"
    "universe"   = "6"
    "everything" = "7"
  }
}

variable "empty_map" {
  type = "map"

  default = {}
}

variable "nested_map" {
  type = "map"

  default = {
    "map_one" = {
      "key_1-1" = "value_1-1"
      "key_1-2" = "value_1-2"
    }

    "map_two" = {
      "key_2-1" = "value_2-1"
      "key_2-2" = "value_2-2"
    }
  }
}

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

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

output "1_map_value_output" {
  value = "${keys(var.map_value)}"
}

output "2_map_function_output" {
  value = "${keys(map("life",list("42"),"the universe",list("six","times","seven")))}"
}

output "3_empty_map_output" {
  value = "${keys(var.empty_map)}"
}

output "4_nested_map_output" {
  value = "${keys(var.nested_map)}"
}

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

#All examples are in variables
terraform apply

Why use it?

There’s a good chance you are going to need the keys in a map to help look up values. Especially if you don’t know what is going to be in that map to begin with. Once you have extracted the keys into a list, now you can use something like contains or element to parse through that list in a conditional logic statement or in a count loop. Lots of fun to be had there.

Lessons Learned

The function does exactly as advertised. It doesn’t mind an empty map or a nested map. With the nested map, you are only going to get the keys of the top level map, and not the keys of the nested maps. Not surprising, but good to know.

Coming up next is the length() function. That might end up being a long post, har-har-har.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.