Terraform – FotD – values()

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

What is it?

Function name: values(map)

Returns: Takes a map and returns the values in the order the keys appear. The values must be strings, not lists or maps.

Example:

variable "map" {
  type = "map"

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

# Returns ["1","2"]
output "value_output" {
  value = "${values(var.map)}"
}

Example file:

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

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

variable "empty_map" {
  type = "map"

  default = {}
}


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

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

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

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

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

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

#All examples are in variables
terraform apply

Why use it?

Usually, you would be more interested in knowing the keys in a map, and then getting the respective values. But there are times you might just want all the values. The returned list may have some duplicates in it, so using the distinct function can help remove those. If you are trying to flip the values and keys, then you can use this function along with keys and zipmap to create a reversed map. You might think the transpose function would do that. But you’d be wrong.

Lessons Learned

The function does exactly as advertised. It doesn’t mind an empty map, but all the values have to be strings. If the value is a map or list, then the function will throw an error.

Coming up next is the zipmap() function. And that will be the final function of this series. Wow!

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.