amazon-web-servicesaws-lambdaamazon-vpc

AWS Lambda triggers SES in VPC


I have a lambda function sitting in a VPC, with the following in/out bound rules. Inbound Rule

OutBound Rule

Inside the function, the goal is to trigger an email, so something like this:

const aws = require('aws-sdk');
const ses = new aws.SES({ region: 'us-west-2' });
                
ses.sendEmail(params, function (err, data) {
    if (err) {
        console.log(err);
    }
});

However; when I trigger the function, there is no error printed, and the task timed out.

Originally the function was sitting out of VPC, and it can successfully send the email.

I've double checked this function's permission, which includes AWSLambdaVPCAccessExecutionRole.

Any one knows what's happening here?


Solution

  • the problem with this is that the lambda function's code has no path to reach the SES endpoint.

    The easiest way to fix this is to give the function access to the Internet. Although you gave the Security Group permission to connect to the internet, cannot reach the SES endpoint because it has no public IP to send the requests from.

    Putting Function behind NAT

    The easiest way to fix this is to:

    1. put a NAT Gateway in the subnet(s) where the function is deployed to,
    2. in the route table of the subnet(s) append a rule to direct all traffic to 0.0.0.0/0 to the NAT Gateway.

    More info about NAT gateways

    Keep in mind that this has the advantage to allow your function to access any internet resource and also the downside of routing the traffic though public Internet.

    Creating an endpoint in your VPC

    This solution, although cleaner and more modern, involves many steps and I suggest you to stick with the first solution.

    A VPC endpoint is essentially a way to reach an AWS service (or a service from AWS's Marketplace) without letting your traffic to leave your VPC.

    This works by assigning a private IP in your VPC to a "private link" to that service.

    If you want to take this path, start reading from this page Interface VPC endpoints.