In this simple guide I’ll break down Terraform Length Function a popular and powerful infrastructure as tool. But is sometimes tricky!
Today Admins can use the built-in Terraform functions to carry out different mathematical calculations linked to a deployment, as well as to execute tasks like encoding and decoding, or capturing and showing timestamps. The Terraform language exclusively supports its built-in functions; there are no options for custom or user-defined functions.
Here’s clear explanations
What Is the Terraform length Function?
Terraform functions are handy tools for tweaking and transforming data in your setups. They enable tasks such as string formatting, math calculations, and handling lists and maps.
With these functions, you can build dynamic and easy-to-manage infrastructure code that follows the DRY (Don’t Repeat Yourself) principle, making it easier to provision and manage your resources.
Terraform functions are utilized to express an argument and return a value of a specific type. You can generalize the built-in functions using the following syntax:
Get exclusive access to all things tech-savvy, and be the first to receive
the latest updates directly in your inbox.
(arg 1, arg 2).
The number and type of arguments that Terraform functions can accept are predefined. However, in some cases, the built-in functions might take undefined arguments – like the min() and max() functions for numeric types.
The inputs for these arguments must be of the same type. Instead of sending a long list of arguments by value, we can use a type list or tuple variable. The syntax for calling the function will now appear as follows.
( …)
The three dots “…” syntax mentioned above is referred to as expansion syntax and is only applicable within functions.
Terraform functions treat sensitive data with care. When you pass an object that contains sensitive information to the function, Terraform designates the output of the entire function as sensitive.
Users cannot create custom functions that introduce additional processing logic beyond what is already included. Terraform serves as a provisioning tool rather than a logic processing compiler or interpreter. The built-in functions encompass all available logic, which engineers need to use creatively.
Length Function Syntax in Terraform
Here’s the Terraform Length Function Syntax:
length(<list | map | string>)
Counting Elements in Lists with length
element(list, index) – Retrieves one item from a list at the specified index. If the index exceeds the total number of items, this function will apply a standard mod algorithm. This function is applicable only to flat lists. Examples:
element(aws_subnet.foo.*.id, count.index)<br>element(var.list_of_strings, 2)
Using length for Maps: Counting Keys
lookup(map, key, [default]) – This function allows you to dynamically search within a map variable. The map parameter must be another variable, like var.amis. If the key is not present in the map, the interpolation will not succeed unless you provide a third argument, default, which should be a string that is returned if the key is missing in the map. Note that this function is applicable only to flat maps and will generate an error for maps containing nested lists or maps.
variable "tags" {
default = {
env = "prod"
dept = "marketing"
}
}
output "tag_keys" {
value = length(var.tags) # returns 2
}
String Length with length
This section is about a Terraform length function related to strings, which help you create and modify strings in your code. This is especially helpful for naming resources, creating tags, and formatting output values.

For example: we can set var.instance_base_name for the base name of our instance and var.env for the environment name in variables in variables.tf.
Here’s a very useful Terraform length function for when you want to count characters vs bytes:
output "gamer_characters" {
value = length("👾🕹️") # returns 2, not byte count
}
Encoding Functions
Terraform includes several built-in functions that handle encoding and decoding of strings. For instance, the base64encode(‘string’) function produces a Base64-encoded string, which is helpful for deploying Azure resources that require Base64-encoded custom scripts for VM setup.
In the example below, the file() function retrieves the content of a script in plain text, which is then encoded using the Base64encode() function and provided to the script attribute of the resource:
resource "azurerm_virtual_machine_extension" "Example" {<br>name = "MyVM"<br>location = "${azurerm_resource_group.test.location}"<br>resource_group_name = "${azurerm_resource_group.test.name}"<br>virtual_machine_name = "${azurerm_virtual_machine.test.name}"<br>publisher = "Microsoft.Azure.Extensions"<br>type = "CustomScript"<br>type_handler_version = "2.0"<br>settings = <
Split Function
The split function in the Terraform Length Function works in contrast to join. It divides a string into a list of smaller strings using a given delimiter, which is helpful for breaking down complicated strings into separate parts.
Syntax:
split(delimiter, string)
- delimiter: The string that separates the main string.
- string: The original string that will be divided into a list.
Some Amazing In-Built Terraform Length Functions
These Terraform Length functions seem more technical but are pretty straightforward to use.
- basename(path) – Returns the last part of a path
- base64gzip(string) – Compresses the specified string using gzip and encodes the result in base64. This is useful for certain resource arguments that accept binary data in base64 format, as Terraform strings must be valid UTF-8.
- compact(list) – Eliminates empty string elements from a list. This can be helpful in various situations, such as when passing combined lists as module variables or when interpreting module outputs. Example: compact(module.my_asg.load_balancer_names)
- concat(list1, list2, …) – Merges two or more lists into one list. Example: concat(aws_instance.db..tags.Name, aws_instance.web..tags.Name)
- distinct(list) – Removes duplicate entries from a list. It retains the first occurrence of each item and discards any following duplicates. This function is applicable only to flat lists. Example: distinct(var.usernames)
- index(list, elem) – Locates the index of a specified element within a list. This function is limited to flat lists. Example: index(aws_instance.foo.*.tags.Name, “foo-test”)
- transpose(map) – Exchanges the keys and list values in a map of lists of strings. For instance, transpose(map(“a”, list(“1”, “2”), “b”, list(“2”, “3”))) results in a value equivalent to map(“1”, list(“a”), “2”, list(“a”, “b”), “3”, list(“b”)).
Conclusion!
Terraform length function is a lightweight powerhouse you can use it to drive dynamic loops guard conditions and make your configs smarter. Implement it consistently and then pair it with Terraform’s iteration tools like count and for_each to build flexible maintainable infrastructure as code.
FAQ’s
1: Can the Terraform length function manage null or empty values?
Yes! empty lists/maps yield 0, while nulls are not allowed and result in errors.
2: Is there a distinction between length and strlen?
Terraform provides only length(). For strings, it gives the count of graphemes (not bytes).
3: What occurs if length is applied to nested collections?
It only counts the top-level elements. To count nested items, use flatten() and then re-count.