cintron
cintron

Reputation: 523

How can I setup an AWS lambda to access resources in two, separate VPCs?

I'm using Terraform to build an API + corresponding lambda functions.

I have some other infrastructure, which I'd like to think is nicely set up (maybe I'm wrong?):

All resources are identical on both VPCs; e.g. there's a test-private-subnet and a prod-private-subnet with exactly the same specs, same for DBs, etc.

Now, I'm working on the API and the lambdas that will power said API.

I don't feel like I need a test & prod API gateway and test & prod lambdas:

But when I try and setup a lambda with the vpc_config block (cause I need it to be associated with the security group that's allowed ingress on the DBs), I get the following error:

Error applying plan:

1 error(s) occurred:

* module.lambdas.aws_lambda_function.api-lambda-users: 1 error(s) occurred:

* aws_lambda_function.api-lambda-users: Error creating Lambda function: InvalidParameterValueException: Security Groups are required to be in the same VPC.
status code: 400, request id: xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx

My lambda config looks like this:

resource "aws_lambda_function" "api-lambda-users" {
  provider = "PROVIDER"
  function_name    = "users"
  s3_key           = "users/${var.lambda-package-name}"
  s3_bucket        = "${var.api-lambdas-bucket}"
  role             = "${aws_iam_role.lambda-role.arn}"
  handler          = "${var.handler-name}"
  runtime          = "${var.lambda-runtime}"

  vpc_config {
    security_group_ids = [
      //"${data.aws_security_group.prod-lambda.id}",
      "${data.aws_security_group.test-lambda.id}"
    ]
    subnet_ids = [
      //"${data.aws_subnet.prod-primary.id}",
      "${data.aws_subnet.test-primary.id}"
    ]
  }
}

Notice I'd ideally like to just specify them, together, in their corresponding lists.

Am I missing something?

Suggestions?

Any help, related or not, is much appreciated.

Upvotes: 1

Views: 2080

Answers (1)

strongjz
strongjz

Reputation: 4491

Lambda running inside a vpc is subject to the same networking "rules" as ec2 instances. So it can't "exist" in two VPC's. If the lambda function needs to talk vpc resources in two separate VPC's you could use something like VPC peering or just run two copies of the function in the two different vpc's.

When you add VPC configuration to a Lambda function, it can only access resources in that VPC. If a Lambda function needs to access both VPC resources and the public Internet, the VPC needs to have a Network Address Translation (NAT) instance inside the VPC and a VPC Peering connection.

Upvotes: 5

Related Questions