Sling Academy
Home/DevOps/Terraform: How to calculate the sum/average/product of a list

Terraform: How to calculate the sum/average/product of a list

Last updated: February 03, 2024

Overview

Terraform by HashiCorp is an extremely powerful tool used in infrastructure as code (IaC) for provisioning and managing cloud services with declarative configuration files. A common inquiry among Terraform users is about performing operations on lists, such as calculating the sum, average, or product. This tutorial will cover just that, utilizing Terraform’s built-in functions to make these calculations easy and effective.

Understanding Lists in Terraform

Before we dive into calculations, it’s vital to understand what lists are in Terraform. Lists are ordered collections of values where each value can be considered an element of that list. They are denoted by square brackets [], and the elements can be of any type, including numbers, strings, or other lists.

Calculating the Sum of a List

The first operation we’ll discuss is calculating the sum of numerical elements in a list. Terraform provides the sum function specifically for this purpose. Here’s a simple example:

locals {
  numbers_list = [1, 2, 3, 4, 5]
}

output "sum_example" {
  value = sum(local.numbers_list)
}

This code snippet creates a list of numbers and then calculates their sum using the sum function. The output would be:

sum_example = 15 

Calculating the Average of a List

To calculate the average, Terraform does not offer a direct function, but you can achieve this by using the sum function and dividing by the length of the list. Here’s an example:

locals {
  numbers_list = [10, 20, 30, 40, 50]
}

output "average_example" {
  value = sum(local.numbers_list) / length(local.numbers_list)
}

This will calculate the average of the numbers in the list. The output of this code will be:

average_example = 30 

Calculating the Product of a List

For calculating the product, Terraform doesn’t provide a direct function like sum. However, you can easily calculate the product of a list’s elements using the reduce function along with a small lamda expression. Here’s how:

locals {
  numbers_list = [1, 2, 3, 4, 5]
}

output "product_example" {
  value = reduce(local.numbers_list, 1, (result, element) => result * element)
}

The reduce function iterates over each element of the list, applying the multiplication operation. The first argument “1” is the initial value. The output for the product will be:

product_example = 120 

Advanced List Operations

Now that we’ve covered basic operations, let’s look at more complex scenarios, such as working with lists of lists or applying these calculations conditionally.

Lists of Lists

Calculations on lists of lists require an extra step of flattening. Here’s how you might calculate the sum of all elements in a nested list:

locals {
  nested_numbers = [[1, 2], [3, 4], [5, 6]]
}

output "nested_sum" {
  value = sum(flatten(local.nested_numbers))
}

This example first flattens the list of lists into a single list and then calculates the sum.

Conditional Operations

Sometimes, you may want to perform calculations only on elements that meet certain criteria. The filter function can be used in combination with calculations to achieve this. For instance, calculating the sum of only the even numbers:

locals {
  numbers_list = [1, 2, 3, 4, 5, 6]
}

output "conditional_sum" {
  value = sum([for i in local.numbers_list : i if i % 2 == 0])
}

This examples uses a for loop combined with an if condition inside a comprehensions list to filter only even numbers before calculating their sum.

Conclusion

In this tutorial, we explored how to perform essential calculations such as the sum, average, and product on lists in Terraform. With these techniques, you can efficiently manipulate list data to meet your infrastructure configuration needs. Whether working with simple lists or diving into more advanced scenarios, Terraform provides the functions to accomplish your goals with ease.

Next Article: Terraform: How to get the length of a list

Previous Article: Sorting Lists in Terraform: A Practical Guide

Series: Terraform Tutorials

DevOps

You May Also Like

  • How to reset Ubuntu to factory settings (4 approaches)
  • Making GET requests with cURL: A practical guide (with examples)
  • Git: What is .DS_Store and should you ignore it?
  • NGINX underscores_in_headers: Explained with examples
  • How to use Jenkins CI with private GitHub repositories
  • Terraform: Understanding State and State Files (with Examples)
  • SHA1, SHA256, and SHA512 in Terraform: A Practical Guide
  • CSRF Protection in Jenkins: An In-depth Guide (with examples)
  • Terraform: How to Merge 2 Maps
  • Terraform: How to extract filename/extension from a path
  • JSON encoding/decoding in Terraform: Explained with examples
  • Sorting Lists in Terraform: A Practical Guide
  • Terraform: How to trigger a Lambda function on resource creation
  • How to use Terraform templates
  • Understanding terraform_remote_state data source: Explained with examples
  • Jenkins Authorization: A Practical Guide (with examples)
  • Solving Jenkins Pipeline NotSerializableException: groovy.json.internal.LazyMap
  • Understanding Artifacts in Jenkins: A Practical Guide (with examples)
  • Using Jenkins with AWS EC2 and S3: A Practical Guide