Search code examples
terraformamazon-sqsterraform-provider-aws

How to selectively prevent Terraform config from being passed based on variable?


Context:

I have a use case where I need to make lots of AWS SQS queues using the aws_sqs_queue resource.

Some of these SQS queues need to be specified to use a DLQ, and some of the queues being made are DLQ's.

In order to specify a target DLQ, one needs to provide a redrive_policy of the form:

redrive_policy = jsonencode({
    deadLetterTargetArn = var.dlq_arn
    maxReceiveCount = var.max_receive_count
})

Problem:

The redrive_policy shouldn't be included if the queue being made is itself a DLQ, since DLQ's don't need another DLQ for themselves.

In my variables.tf I specify the type of deadLetterTargetArn as string with a default of null.

I fear that this will result in a DLQ failing to be created because no deadLetterTargetArn gets passed in but a maxReceiveCount is still expected and the redrive_policy will become invalid JSON.

Should I be using a conditional here? What is the correct approach for selectively enabling certain parts of config?


Solution

  • Should I be using a conditional here?

    Yes. That's exactly what you should do:

    redrive_policy = dlq_arn != null ? jsonencode({
        deadLetterTargetArn = var.dlq_arn
        maxReceiveCount = var.max_receive_count
    }) : null