terraformhcl

How to get the product of a terraform list


I was wondering if there's a way to get the product of a list of numbers in Terraform such that you get the product of all of the elements of the list as an output.

I've been trying it out with setproduct and flatten functions but haven't been able to get it working. My use case would look like something the following:

locals {
    productList = [1,2,3,4]
    product = 24
}

And to be able to use that variable output elsewhere as a result. Any tips would be highly appreciated, thanks!


Solution

  • In order for this to be possible in Terraform, there would need to be a function analogous to the sum function which takes a list of arbitrary length and returns the product of all of the numbers in the list.

    The only built-in facility for multiplication is the * operator, which is not applicable here because it applies to exactly two numbers and so you can't use it to multiply the elements of a dynamic-length list of numbers.

    However, Terraform allows extending the language with additional functions in provider plugins. It would be possible to write a provider which offers a function that takes a list of numbers and returns the product of all of those numbers, and then you'd be able to call that function from your Terraform module by depending on that provider.

    There's documentation on how to build a provider that offers a function in Plugin Development - Functions.