Creating SG rules dinamically in TF

I have a problem that can’t solve in TF. I’ll try my best to explain:

I want to create security group rules to allow traffic from different node_groups dinamically to each other (imagine allowing ssh from each other of the node groups). I have the SG id’s inside a list called “ng_ids”. So, I need “length(ng_ids)*(length(ng_ids)-1)” amount of SG rules (so, if a have 3 node groups, I need 6 SG rules).

The algorithm would be something like this:

rules = []
k = 0
for i in [ng_ids]:
	ng_ids_aux = ng_ids - ng_ids[i] # this basically substracts ng in i from the ng_ids_aux list
	for j in [ng_ids_aux]: # for each of the others SGs, excluding the one in "i"
		rules[k] = "from SG[ng_ids[i]] ---> SG[ng_ids_aux[j]] # create a rule from SG[i] to each of the SG in "j"
		k = k + 1 # go the next rule

I know HCL isn’t exactly a programming languaje, but is there a way to hack the matrix in order to make this happen?

I solved it!

variable "sg_ids" {
  type    = list
  default = ["sg-11111111","sg-22222222","sg-33333333","sg-44444444","sg-55555555"]
}
locals {
  auxiliar = setproduct( var.sg_ids , var.sg_ids)
}
output "auxiliar" {
  value = local.auxiliar
}
provider "aws" {
  region = "us-east-1"
}
resource "aws_security_group_rule" "node_group" {
  count                    = length(local.auxiliar)
  type                     = "ingress"
  description              = "Allowed to communicate with all nodes group"
  protocol                 = "-1"
  from_port                = 0
  to_port                  = 0
  # Allowed to communicate with managed nodes group
  security_group_id        = element(concat(element(concat(local.auxiliar), count.index)) , count.index )
  source_security_group_id = element(concat(element(concat(local.auxiliar), count.index)) , count.index + 1 )
}

And sg_ids can be as small as 1, and as big as 1 millon :joy: