0
0
TerraformHow-ToBeginner · 3 min read

How to Use Length Function in Terraform: Syntax and Examples

In Terraform, use the length() function to find the number of items in a list, characters in a string, or keys in a map. Simply pass the collection or string inside length() to get its size as a number.
📐

Syntax

The length() function takes one argument, which can be a list, string, or map. It returns the count of elements or characters.

  • length(list): Returns the number of items in the list.
  • length(string): Returns the number of characters in the string.
  • length(map): Returns the number of keys in the map.
terraform
length(collection_or_string)
💻

Example

This example shows how to use length() with a list, a string, and a map. It outputs the size of each.

terraform
variable "example_list" {
  default = ["apple", "banana", "cherry"]
}

variable "example_string" {
  default = "hello"
}

variable "example_map" {
  default = {
    key1 = "value1"
    key2 = "value2"
  }
}

output "list_length" {
  value = length(var.example_list)
}

output "string_length" {
  value = length(var.example_string)
}

output "map_length" {
  value = length(var.example_map)
}
Output
list_length = 3 string_length = 5 map_length = 2
⚠️

Common Pitfalls

Common mistakes include:

  • Passing a non-collection or non-string value causes errors.
  • Expecting length() to count nested elements; it only counts top-level items.
  • Using length() on null values results in errors.

Always ensure the input is a valid list, string, or map.

terraform
/* Wrong: passing a number causes error */
output "wrong_length" {
  value = length(123)
}

/* Right: pass a string or list */
output "right_length" {
  value = length("123")
}
📊

Quick Reference

Input TypeWhat length() Returns
ListNumber of items in the list
StringNumber of characters in the string
MapNumber of keys in the map

Key Takeaways

Use length() to get the count of items in lists, characters in strings, or keys in maps.
Pass only lists, strings, or maps to length() to avoid errors.
length() counts only top-level elements, not nested ones.
Avoid passing null or unsupported types to length().
Use length() outputs to control resource creation or conditions in Terraform.