Search code examples
terraform

How to compute the cumulative sum of a list in terraform?


Is it possible to use terraform to compute the cumulative sum of a list? There is the sum function, but I am looking for the cumulative sum.

Example:

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

The desired output would be: [1, 3, 6, 10, 15]


The equivalent python code would be:

from numpy import cumsum

print(cumsum([1, 2, 3, 4, 5]))

It prints: [ 1 3 6 10 15]


Solution

  • You can use a combination of range and slice functions to get the desired result:

    • range(max): generates a list of numbers using a start value (from 0 to max - 1)
    • slice: extracts some consecutive elements from within a list

    Example:

    locals {
      values  = [1, 2, 3, 4, 5]
      indexes = range(length(local.values)) # [0, 1, 2, 3, 4]
    
      cumulative_sum_list = [
        for i in local.indexes :
        # For each index, sum the numbers from the start of the list to the current index
        sum(slice(local.values, 0, i + 1))
      ]
    }
    
    output "cumulative_sum_list" {
      value       = local.cumulative_sum_list
      description = "The cumulative sum of the values in the list"
    }
    

    Running terraform plan:

    Changes to Outputs:
      + cumulative_sum_list = [
          + 1,
          + 3,
          + 6,
          + 10,
          + 15,
        ]