Terraform Length Function: Examples For Lists, Maps & Strings
Leveraging functions effectively enhances flexibility and streamlines resource management in any Terraform environment. Instead of hardcoding values, functions enable dynamic interactions between different parts of your code, making it more scalable and maintainable. The length() function in Terraform is a simple yet powerful tool for managing lists, maps, and strings within your configurations. It helps determine the size of these data structures, making it useful for conditionals, loops, and validations. In this article, we'll break down how length() works, its practical applications, and common scenarios where it enhances Terraform workflows. What are Terraform functions? Terraform comes packed with built-in functions that let you manipulate data, making your configurations more dynamic, reusable, and tailored to your environment. Whether you need to format strings, transform data types, or apply conditional logic, Terraform functions give you greater control over how data is processed and utilized. At a high level, these functions let you: Work with strings - Easily concatenate, split, or replace text using join, split, and replace. Handle numbers - Round values up or down and find the max/min with ceil, max, and min. Manage collections - Extract values from lists/maps with length and keys, simplify complex structures using flatten, and merge multiple lists/maps with merge. Process time-based data - Use timeadd and timestamp to handle date/time operations. Convert data formats - Encode data with base64encode or transform it into JSON with jsonencode. Terraform functions also integrate seamlessly with expressions, loops (for), and constructs like for_each and [count](https://spacelift.io/blog/terraform-count), making them a powerful tool for automation. By leveraging these functions, you can build scalable, adaptable configurations that respond dynamically to changing inputs---maximizing efficiency and flexibility in your infrastructure. Read more: Terraform Functions, Expressions, Loops What is the length function in Terraform? The length function in Terraform helps you determine the size of a string, list, or map by returning the number of characters, elements, or keys, respectively. This function is particularly useful when validating input sizes, such as ensuring a list or map contains enough elements before provisioning a resource. It also pairs well with the count construct, allowing you to dynamically create multiple resources based on input size. A common use case is managing firewall rules, where security groups must be defined based on a specific number of inputs. The length function can also help simplify your Terraform workflows and create a more dynamic environment, which we will explore in more detail in this article. How to use the Terraform length function Here is the simple syntax of the length function: length(value) In this case, the value can be a string, list, or map, which can be passed in through a variable. 1. Using the length function with a string Let's demonstrate the behavior of the length function with a simple example: variable "mystring" { default = "helloworld" } The output of the variable using the length function will give you "10". output "number_in_string" { value = length(var.mystring) } number_in_string = 10 We can also perform some checks on this value and output an alert as the following: output "is_string_too_long" { value = length(var.mystring) > 5 ? "string is too long" : "string is valid" } Giving us: is_string_too_long = "string is too long" 2. Using the length function with a list You can also use the Terraform length function with a list: variable "mylist" { default = [ "hello", "world" ] } The output of the variable using the length function against the list will give you "2". output "number_in_list" { value = length(var.mylist) } number_in_list = 2 You can also perform checks on a list, as we did with strings: variable "subnet_ids" { default = ["subnet-1"] } output "validate_subnet" { value = length(var.subnet_ids) >= 2 ? "Valid subnet count" : "Error: At least 2 subnets required" } Because we only have one subnet in our list, we will get the following output: validate_subnet = "Error: At least 2 subnets required" 3. Using the length function with a map Let's see an example of using the Terraform length function with a map: variable "mymap" { default = { Map1 = "value1" Map2 = "value2" } } The output of the variable using the length function against the map will give you "2". output "number_in_map" { value = length(var.mymap) } number_in_map = 2 With maps, we can use some conditionals to grab the length of a specific key in a map: variable "users" { default = { goku = "admin" gohan = "user" vegeta = "admin" trunk

Leveraging functions effectively enhances flexibility and streamlines resource management in any Terraform environment. Instead of hardcoding values, functions enable dynamic interactions between different parts of your code, making it more scalable and maintainable.
The length()
function in Terraform is a simple yet powerful tool for managing lists, maps, and strings within your configurations. It helps determine the size of these data structures, making it useful for conditionals, loops, and validations. In this article, we'll break down how length() works, its practical applications, and common scenarios where it enhances Terraform workflows.
What are Terraform functions?
Terraform comes packed with built-in functions that let you manipulate data, making your configurations more dynamic, reusable, and tailored to your environment. Whether you need to format strings, transform data types, or apply conditional logic, Terraform functions give you greater control over how data is processed and utilized.
At a high level, these functions let you:
- Work with strings - Easily concatenate, split, or replace text using
join
,split
, andreplace
. - Handle numbers - Round values up or down and find the max/min with
ceil
,max
, andmin
. - Manage collections - Extract values from lists/maps with
length
andkeys
, simplify complex structures usingflatten
, and merge multiple lists/maps withmerge
. - Process time-based data - Use
timeadd
andtimestamp
to handle date/time operations. - Convert data formats - Encode data with
base64encode
or transform it into JSON withjsonencode
.
Terraform functions also integrate seamlessly with expressions, loops (for
), and constructs like for_each
and [count](https://spacelift.io/blog/terraform-count)
, making them a powerful tool for automation. By leveraging these functions, you can build scalable, adaptable configurations that respond dynamically to changing inputs---maximizing efficiency and flexibility in your infrastructure.
Read more: Terraform Functions, Expressions, Loops
What is the length function in Terraform?
The length
function in Terraform helps you determine the size of a string, list, or map by returning the number of characters, elements, or keys, respectively. This function is particularly useful when validating input sizes, such as ensuring a list or map contains enough elements before provisioning a resource. It also pairs well with the count construct, allowing you to dynamically create multiple resources based on input size.
A common use case is managing firewall rules, where security groups must be defined based on a specific number of inputs.
The length function can also help simplify your Terraform workflows and create a more dynamic environment, which we will explore in more detail in this article.
How to use the Terraform length function
Here is the simple syntax of the length function:
length(value)
In this case, the value can be a string, list, or map, which can be passed in through a variable.
1. Using the length function with a string
Let's demonstrate the behavior of the length function with a simple example:
variable "mystring" {
default = "helloworld"
}
The output of the variable using the length function will give you "10".
output "number_in_string" {
value = length(var.mystring)
}
number_in_string = 10
We can also perform some checks on this value and output an alert as the following:
output "is_string_too_long" {
value = length(var.mystring) > 5 ? "string is too long" : "string is valid"
}
Giving us:
is_string_too_long = "string is too long"
2. Using the length function with a list
You can also use the Terraform length function with a list:
variable "mylist" {
default = [ "hello", "world" ]
}
The output of the variable using the length function against the list will give you "2".
output "number_in_list" {
value = length(var.mylist)
}
number_in_list = 2
You can also perform checks on a list, as we did with strings:
variable "subnet_ids" {
default = ["subnet-1"]
}
output "validate_subnet" {
value = length(var.subnet_ids) >= 2 ? "Valid subnet count" : "Error: At least 2 subnets required"
}
Because we only have one subnet in our list, we will get the following output:
validate_subnet = "Error: At least 2 subnets required"
3. Using the length function with a map
Let's see an example of using the Terraform length function with a map:
variable "mymap" {
default = {
Map1 = "value1"
Map2 = "value2"
}
}
The output of the variable using the length function against the map will give you "2".
output "number_in_map" {
value = length(var.mymap)
}
number_in_map = 2
With maps, we can use some conditionals to grab the length of a specific key in a map:
variable "users" {
default = {
goku = "admin"
gohan = "user"
vegeta = "admin"
trunks = "user"
}
}
output "admin_count" {
value = length({ for k, v in var.users : k => v if v == "admin" })
}
Giving us the following:
admin_count = 2
These are a few simple examples of how you can use the length function with variable data types.
In the next section, we will explore how to maximize the length function's use in real-world scenarios with our cloud providers.