AWS: Lambda, ElastiCache(memcache), aws-serverless-express (No EC2, only VPC) setup tutorial

Our team tries to move our express application to Lambda, and we found https://github.com/awslabs/aws-serverless-express/tree/master/example#steps-for-running-the-example to start off.

So, we followed the steps in this tutorial. Before you run npm run setup ,

  1. you need to make sure you are using the latest node(8.0.0) and npm(5.0.0).
  2. You need to run find .-exec touch {} \;
  3. Now you can run npm run setup .

If you take a look at package.json file, you will know that npm run setup helps us create a S3 bucket, create a lambda function, create rules for the lambda function, zip our app, deploy our app to lambda, etc. So, where is our ElastiCache?

  1. We can go to AWS console to create an ElastiCache manually. Pay attention when you select the Subnet Group for your ElastiCache. You can also create an ElastiCache Cluster via aws-cli.

Once we got the endpoint of ElastiCache, in app.js we can import connect-memcached.

//app.js
const session = require(“express-session”)
const cookieParser = require(‘cookie-parser’)
const MemcachedStore = require(‘connect-memcached’)(session)
app.use(cookieParser('test'));
app.use(session({
secret: 'test',
key: 'test',
proxy: 'true',
resave: 'true',
saveUninitialized: 'true',
store: new MemcachedStore({
hosts: [<ElastiCacheEndpoint>:11211],
})
}));

2. Go to AWS console -> IAM -> role. You will see one of your roles is AwsServerlessExpressStack-LambdaExecutionRole-xxxxx Edit this policy.

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
"ec2:CreateNetworkInterface",
"ec2:DescribeNetworkInterfaces",
"ec2:DeleteNetworkInterface"
],
"Resource": "*"
}
]
}

3. Go to AWS console -> VPC. From the left side menu, you see subnets . Click subnets . Now you will see a list of your subnets.

aws lambda update-function-configuration — function-name AwsServerlessExpressStack-AwsServerlessExpressFunc-xxxxx — vpc-config SubnetIds=<SubnetIds split with commas>,SecurityGroupIds=<SecurityGroupId>

Now, you can zip your code again and deploy to Lambda, then you go to CloudFormation -> Look for AwsServerlessExpressStack -> Outputs -> ApiUrl. You should see your deployment successfully.