Creating a Cartesian Product in Terraform

Suraj Narwade
Suraj in Cloud
Published in
2 min readMar 16, 2021
taken from: https://www.terraform.io/logos.html

For one of my terraform tasks, I needed all the possible combinations of elements from all given sets. For example, there are two sets.

set1 = ["a","b","c"]
set2 = [1,2]

The expected result is,

[["a",1], ["a",2],["b",1],["b",2],["c",1],["c",2]]

After searching about this, I got to know that such a concept is called the Cartesian Product. From the Wikipedia definition,

the Cartesian product of two sets A and B, denoted A × B, is the set of all ordered pairs (a, b) where a is in A and b is in B.

In my mind, I was thinking there has to be a nested for looping & tried something and failed miserably.

But we think from the Programmer perspective, but Terraform is not a Programming Language.

Hence, After searching a lot, I came across this amazing function called setproduct, which basically provides Cartesian product out of the box,

locals{
b = ["a", "b", "c"]
a = [1, 2]
}
output "example" {
value = setproduct(local.b, local.a)}

and output is amazing and lifesaving,

[
[
"a",
1,
],
[
"a",
2,
],
[
"b",
1,
],
[
"b",
2,
],
[
"c",
1,
],
[
"c",
2,
],
]

If you have successfully created cartesian product without using setproduct(), do comment here :)

Thanks, Have a lovely day :)

--

--

Suraj Narwade
Suraj in Cloud

All things Cloud, Containers & Developer Experience