lipsum
lipsum

Reputation: 969

Is there way to ignore optional field in terraform module when value is not specified?

I'm managing AWS lambda functions with terraform module. Now I want to add dead_letter_config to one of the lambda functions, but keep other functions unchanged.

I'm trying to add dead_letter_config field (which is optional in aws_lambda_function resource) to the module, but I can't find how I can make dead_letter_config field available in only a specific lambda function, and make that field ignored in other callers.
My terraform is v0.12.28, so I tried to use null default value on a variable.

resource "aws_lambda_function" "lambda" {
...
  dead_letter_config {
    target_arn = var.dead_letter_config_target
  }
variable "dead_letter_config_target" {
  default     = null
  type        = string
}

But target_arn field is required under dead_letter_queue field, so terraform plan fails.

Error: "dead_letter_config.0.target_arn": required field is not set

Is there any good way to ignore an entire field conditionally?

Upvotes: 2

Views: 2061

Answers (2)

Martin Atkins
Martin Atkins

Reputation: 74109

The Terraform "splat" operator [*] can be used as a convenient way to translate from a value that might be either set or null into either a zero-length or one-element list, which is then more convenient to use with the collection-oriented features of the Terraform language like dynamic blocks for example:

resource "aws_lambda_function" "lambda" {
  # ...
  
  dynamic "dead_letter_config" {
    for_each = var.dead_letter_config_target[*]

    content {
      target_arn = each.value
    }
  }  
}

Upvotes: 2

Marcin
Marcin

Reputation: 238081

Yes. You can use dynamic block for that. Basically, when the dead_letter_config_target is null, no dead_letter_config will be created. Otherwise, one dead_letter_config block is going to be constructed.

For example, the modified code could be:

resource "aws_lambda_function" "lambda_tf" {

  # other attributes
  
  dynamic "dead_letter_config" {

    for_each = var.dead_letter_config_target != null ? toset([1]) : toset([])

    content {
      target_arn = var.dead_letter_config_target
    }
  }  
}

P.S.

For the DLQ, you will obviously need to setup the permissions in the lambda execution role.

Upvotes: 5

Related Questions