Skip to main content

Using Collection Functions

1. Using concat Function

The concat function in Terraform is used to combine multiple lists into a single list. It accepts any number of lists as arguments and returns a new list that contains all elements from the input lists in the order they were provided.

Argument Type Description
list1, list2, ... List of any type Lists to be concatenated. Can accept zero or more lists.

Example: Concatenating Lists

locals {
  list1 = [1, 2, 3]
  list2 = [4, 5, 6]
  combined_list = concat(local.list1, local.list2)
}

output "combined" {
  value = local.combined_list
}

Example: Concatenating Lists with Different Types

locals {
  string_list = ["apple", "banana"]
  number_list = [1, 2, 3]
  mixed_list = concat(local.string_list, local.number_list)
}

output "mixed" {
  value = local.mixed_list
}
Note: The concat function does not modify the original lists; it creates a new list containing all elements from the input lists.

2. Using contains Function

Function Description Usage Examples
contains(list, value) Checks if a list contains a specific value Returns true if the value is found in the list, false otherwise contains(["a", "b", "c"], "b") // true
contains(map, key) Checks if a map contains a specific key Returns true if the key is found in the map, false otherwise contains({"a": 1, "b": 2}, "a") // true

3. Using distinct Function

The distinct function in Terraform is used to remove duplicate values from a list, returning a new list with only unique elements. It's particularly useful when working with lists that may contain repeated values and you need to ensure uniqueness.

Argument Type Description
list list(any) A list of any type from which duplicates should be removed.

Example: Removing Duplicates from a List

locals {
  original_list = [1, 2, 2, 3, 4, 4, 5]
  unique_list   = distinct(local.original_list)
}

output "unique_list" {
  value = local.unique_list
}
Note: The order of elements in the resulting list is not guaranteed to match the order in the input list. The function preserves the first occurrence of each element.

4. Using flatten Function

The flatten function in Terraform is used to convert a nested list into a single-level list. It takes a list of lists and returns a flattened list containing all elements from the nested lists.

Argument Type Description
list list(list(any)) A list of lists to be flattened.

Example: Flattening a Nested List

locals {
  nested_list = [
    [1, 2],
    [3, 4],
    [5, 6]
  ]
  flattened_list = flatten(local.nested_list)
}

output "flattened" {
  value = local.flattened_list
}

Example: Flattening Lists with Different Types

locals {
  mixed_list = [
    [1, 2],
    ["three", "four"],
    [5.0, 6.0]
  ]
  flattened_mixed = flatten(local.mixed_list)
}

output "mixed_flattened" {
  value = local.flattened_mixed
}
Note: The flatten function works recursively, meaning it can handle lists nested more than one level deep. For example, flatten([[1, 2], [[3, 4], [5, 6]]]) will result in [1, 2, [3, 4], [5, 6]] because it only flattens one level deep.
Warning: If the input list contains non-list elements, Terraform will throw an error. Ensure all elements in the input list are lists.

5. Using length Function

Function Description Examples
length() Returns the number of elements in a list, tuple, or string.
length(["a", "b", "c"]) // 3
length("hello") // 5

Example: Calculating List Length

resource "aws_instance" "web" {
  count = length(var.instance_names)
  instance_type = "t2.micro"
}

Example: String Length Validation

locals {
  name_length = length(var.instance_name)
}

resource "aws_instance" "web" {
  instance_type = "t2.micro"
  count = local.name_length > 0 ? 1 : 0
}

6. Using element and index Functions

Function Description Example Notes
element(list, index) Returns the element at the specified index in a list element(["apple", "banana", "cherry"], 1) // Returns "banana" Index is zero-based. If index is out of bounds, Terraform throws an error
index(list, value) Returns the index of a given element in a list index(["apple", "banana", "cherry"], "cherry") // Returns 2 If value is not found, Terraform throws an error. Returns zero-based index

7. Using keys and values Functions

Function Description Example Notes
keys() Returns a list of keys from a map or object keys(var.my_map) Useful for iterating over map keys
values() Returns a list of values from a map or object values(var.my_map) Useful for iterating over map values

Example: Using keys() and values()

variable "servers" {
  type = map(object({
    ami = string
    instance_type = string
  }))
  default = {
    "web" = {
      ami = "ami-12345678"
      instance_type = "t2.micro"
    }
    "db" = {
      ami = "ami-87654321"
      instance_type = "t2.small"
    }
  }
}

resource "aws_instance" "server" {
  for_each = var.servers
  ami = each.value.ami
  instance_type = each.value.instance_type
}
Note: The keys() and values() functions are particularly useful in conjunction with for_each loops to dynamically create resources based on map contents.

8. Using lookup and try Functions

Function Description Syntax Example
lookup Returns a value from a map or list using a key or index lookup(map, key, default) Example: Using lookup
locals {
  map = {
    "key1" = "value1"
    "key2" = "value2"
  }
  value = lookup(local.map, "key1", "default")
}
try Safely evaluates an expression and returns a default value if it fails try(expression, default) Example: Using try
locals {
  value = try(var.nonexistent_var, "default_value")
}
Note: The lookup function is useful for safely accessing map values, while try provides a way to handle potentially failing expressions gracefully.

9. Using merge Function

Function Signature Description Examples
merge() merge(map1, map2, ...) Merges multiple maps into a single map. If keys overlap, the last map's value takes precedence. merge({ a = 1 }, { b = 2 }) // Returns: { a = 1, b = 2 }
merge() merge(map1, map2, ...) Handles nested maps by merging keys recursively. merge({ a = { x = 1 } }, { a = { y = 2 } }) // Returns: { a = { x = 1, y = 2 } }

Example: Merging Maps in Terraform Configuration

locals {
  base_config = {
    name        = "web-app"
    environment = "prod"
  }

  override_config = {
    name        = "web-app-staging"
    instance_type = "t3.medium"
  }

  merged_config = merge(local.base_config, local.override_config)
}

output "merged_name" {
  value = local.merged_config.name
}
Note: The merge function is particularly useful for overriding default configurations with environment-specific values.
Warning: When merging maps with overlapping keys, the last map in the argument list takes precedence.

10. Using range Function

Argument Description Default Example
start Starting value of the range (inclusive) 0 range(5)
end Ending value of the range (exclusive) 0 range(2, 8)
step Increment between values in the range 1 range(0, 10, 2)

Example: Basic usage of range function

resource "aws_instance" "web" {
  count = length(range(3))
  ami   = "ami-12345678"
  instance_type = "t2.micro"
}

Example: Using range with custom start and step

locals {
  numbers = range(10, 20, 2)
}

output "numbers" {
  value = local.numbers
}

11. Using reverse and sort Functions

Function Description Example Notes
reverse() Reverses the order of elements in a list
reverse(["a", "b", "c"]) 
// Returns: ["c", "b", "a"]
Works with any list type
sort() Sorts elements in a list alphabetically or numerically
sort(["c", "a", "b"]) 
// Returns: ["a", "b", "c"]
Sorts numerically if all elements are numbers

Example: Reversing and Sorting Lists

locals {
  original_list = ["apple", "banana", "cherry"]
  reversed_list = reverse(local.original_list)
  sorted_list   = sort(local.original_list)
}

output "reversed" {
  value = local.reversed_list
  // Output: ["cherry", "banana", "apple"]
}

output "sorted" {
  value = local.sorted_list
  // Output: ["apple", "banana", "cherry"]
}

12. Using slice Function

Argument Description Example
list List to slice slice(["a", "b", "c", "d"], 1, 3)
start Start index (inclusive) slice(["a", "b", "c", "d"], 1, 3)
end End index (exclusive) slice(["a", "b", "c", "d"], 1, 3)

Example: Slicing a List

output "slice_output" {
  value = slice(["a", "b", "c", "d"], 1, 3)
}
Note: The slice function returns a new list containing elements from the original list between the specified start and end indices.

Was this article helpful?