2

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This becomes a good chance to learn dynamic block.
2

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
    }
  }  
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.