简体   繁体   中英

AWS Lambda triggers SES in VPC

I have a lambda function sitting in a VPC, with the following in/out bound rules. 入站规则

出站规则

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?

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 .

I did a lot of research how to solve the "Lambda won't be able to access internet/SES/S3/..." issue, because I don't want to spend money on a NAT Gateway . Here is my solution.

  1. You need 2 Lambdas (1 in the VPC and 1 outside of the VPC)
  2. My first Lambda does the VPC jobs (in my case request RDS)
  3. The result of my first lambda I post to an SNS topic (You need to set VPC endpoint for SNS )
  4. A SQS queue is subscribed to the SNS topic
  5. My second Lambda listens to the SQS queue and does the rest of the "Internet job"

Like this I do not have to setup a NAT gateway and save those 30 bucks each month. And like this you can call SES functions like listIdentity and so on...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM