Using AWS Lambda Function to Create AMI at Runtime

AWS Lambda is a very powerful service. You can write numerous Lambda functions to cater your requirement. This articles explains a real world scenario which uses Lambda function to achieve the intended result.

The Infrastructure in place:

Before I dig deep into Lambda function, let’s understand the existing AWS infra and the requirements. I had a very simple environment with AutoScaling groups configured to take care of Web Servers running on Windows environment. Our SQL Server was running on RDS which we migrated to EC2 recently ( a different story altogether ). Our code was hosted on BitBucket and automatic deployments were configured using AWS CodeDeploy.

The Requirements: 

Our basic requirement was to create a new AMI every time a successful deployment is done. We were also looking to update our AutoScaling group with the new AMI. 

The Solution: 

Here begins the fun part. Let’s start with BitBucket and move with the flow. Once the code is ready to be deployed, go to BitBucket and click Deploy To AWS button. More on configuring BitBucket with AWS CodeDeploy can be found here.

That will pass the control to AWS CodeDeploy which will make the deployment on all the instances currently running as part of Auto Scaling group. Now is the time when you have to think about create an AMI and update Auto Scaling group. To achieve this, I have used Amazon SNS service. After every successful deployment, CodeDeploy service will send a message to SNS which in turn trigger AWS Lambda function and this function will take care of all the requirements we had.

Below is the detailed explanation about this function. Continue reading