I’m trying to use the serverless framework to create a Lambda function that can access an Elasticache cluster, as well as call out to the internet.
I’ve got as far as configuring serverless.yml
to create the Lambda function, create the Elasticache cluster (memcached engine), and finally to create a VPC and place both the Lambda function and Elasticache cluster within it (otherwise, they cannot communicate).
I understand that things within a VPC do not have access to the internet, and from researching around the topic I’ve come to the conclusion that the best practice way of handling this is to create a NAT gateway for the VPC that will allow it external access.
I can see how to do this within the AWS Console, however I’d like to stick to defining this within serverless.yml
to avoid any manual infrastructure setup.
- Is it possible to create a NAT gateway within
serverless.yml
? - Is creating a NAT gateway the correct way of doing this? (Are there better options?)
Additional information
In getting to the point I’m currently at, I heavily copied from one of the serverless examples (it’s a Java based example, but the concept and service definition is the same). It creates a Lambda function, an Elasticache cluster, and puts them in a VPC so they can communicate. I believe it has the same issue whereby the Lambda function cannot access the internet. https://github.com/mugglmenzel/serverless-examples-cached-rds-ws/blob/master/serverless.yml
2
Answers
You have to configure a NAT instance or a managed NAT Gateway to provide internet access to your Lambdas inside the VPC. You may have to use the resource section of your
serverless.yml
file to create the NAT Gateway / NAT Instance resource.Have a look at the resources section of the Serverless Framework documentation. These resources will be added to the cloudformation stack upon
serverless deploy
So you can add the Cloudformation template for a NAT Gateway inside the resource section.
For Example,
Here is a link to a complete CloudFormation snippet of Lambda inside VPC.
I created an example of lambda with vpc, eslaticache and NAT gateway. You can check at
https://github.com/ittus/aws-lambda-vpc-nat-examples