dynamic block to skip vpc config to lambda

Viewed 21

I would like to skip adding a vpc to lambda in certain env. The current terraform code to update vpc is like below

data "aws_subnet" "lambda-private-subnet_1" {
  availability_zone = var.environment_type_tag != "prd" ? "us-east-1a" : null
  dynamic "filter" {
    for_each = var.environment_type_tag == "prd" ? [] : [1]
    content {
      name   = "tag:Name"
      values = [var.subnet_value]
    }
  }
}
resource "aws_lambda_function" "tests" {
  dynamic "vpc_config" {
    for_each = var.environment_type_tag == "prd" ? [] : [1]
    content {
      subnet_ids         = [data.aws_subnet.lambda-private-subnet_1.id]
      security_group_ids = [var.security_group]
    }
  }
}

During 'terraform plan', the output is like below

##[error][1m[31mError: [0m[0m[1mmultiple EC2 Subnets matched; use additional constraints to reduce matches to a single EC2 Subnet[0m

I would like to skip the 'data "aws_subnet"' block if its 'prd' environment type.

1 Answers

So there are four different questions in this question. We can attempt to answer each one:

  1. dynamic block to skip vpc config to lambda

This is already occurring with the given code. The dynamic blocks are "skipped" in prd with the current code.

  1. I would like to skip adding a vpc to lambda in certain env.

If you mean "subnet" instead of "vpc", then this is also already occurring with the given code. Otherwise, please update with the vpc config.

  1. ##[error][1m[31mError: [0m[0m[1mmultiple EC2 Subnets matched; use additional constraints to reduce matches to a single EC2 Subnet[0m

The error message is due to the fact that your filters match multiple subnets outside of prd, and therefore you need to constrain the filter conditions.

  1. I would like to skip the 'data "aws_subnet"' block if its 'prd' environment type.

You just need to extend your current code to make the data optional:

data "aws_subnet" "lambda-private-subnet_1" {
  for_each = var.environment_type_tag == "prd" ? [] : toset(["this"])
  ...
}

You can then remove the for_each from the dynamic block in the resource as it is redundant, and update the attribute references with elements accordingly:

subnet_ids = [data.aws_subnet.lambda-private-subnet_1["this"].id]
Related