Search code examples
terraformterraform-provider-aws

How do add a dynamic parameter in Terraform?


I create some AWS resources in Terraform in a loop by utilising the count feature.

However, I have come accross a scenario I can't seem to find an answer for:

Have a look at my sample code to demonstrate this:

JSON file I inject to be used for the count. This is the var.services in the Terraform code:

[
    {
        "service-name"   : "frontendapp",
        "daemon"         : false
    },
    {
        "service-name"   : "backendapp",
        "daemon"         : true
    }
]

The Terraform code:

resource "aws_ecs_service" "services" {
  count           = length(var.services)
  name            = "${var.services[count.index].service-name}"
  cluster         = aws_ecs_cluster.my-ecs-cluster.id
  task_definition = aws_ecs_task_definition.my-task-definition.arn
  desired_count   = 1
  deployment_minimum_healthy_percent = 100
  scheduling_strategy =  var.services[count.index].daemon == true ? "DAEMON" : "REPLICA"
}

What I need:

Much like the scheduling_strategy in the Terraform code, I need to have a condition for the desired_count but instead of giving it a value, I need to omit this line entirely when var.services[count.index].daemon == true

I read somewhere that giving it the value of null would do it but that's not the case.


Solution

  • Use null as the other value, that is identical to omitting the line:

    desired_count = var.services[count.index].daemon ? 1 : null
    

    a value that represents absence or omission. If you set an argument of a resource to null, Terraform behaves as though you had completely omitted it — it will use the argument's default value if it has one, or raise an error if the argument is mandatory. null is most useful in conditional expressions, so you can dynamically omit an argument if a condition isn't met.