Home > Net >  Terraform conditional iteration
Terraform conditional iteration

Time:11-17

I would like to create a dynamic resource with for_each as well I would like to implement a resource creation condition, however by some reason which I don't understand, the resource creation condition is not working as expected.

The logic is very simple: I've a list of objects, each object is resource, therefore in each object a have a bool variable that enables creation of a resource.

resource "aws_autoscaling_group" "aws_asg"  {
   for_each = { for key, value in var.parameters : key => value if flatten([ for x in var.parameters : x.init ]) }
}

The problem in flatten([ for x in var.parameters : x.init ]), the resource takes first element, and ignores next element:

    x = [
        true,
        false,
    ]

Here is var.parameters

   parameters = [
       # Runner 1
       {
            init    = true
            name    = "test-runner-1"

            scaling = {
                    desired     = 3
                    maximum     = 9
                    minimum     = 3
            }
       },

       # Runner 2
       {
            init    = false
            name    = "test-runner-2"

            scaling = {
                    desired     = 3
                    maximum     = 9
                    minimum     = 3
            }
       }
   ]
}

Any idea how to map each boolean to resource creation?

CodePudding user response:

If you want to conditionally loop through your parameters, then it should be:

resource "aws_autoscaling_group" "aws_asg"  {
   for_each = { for key, value in var.parameters : key => value if value.init }
}
  • Related