Use AWS Lambda to Stop EC2 Instances | Linux

Companies everywhere are beginning to use AWS , a serverless technology, to run code without the overhead that often comes with maintaining a complete server. The benefits can be huge. In this post from Chad Crowell, back when he was a DevOps Engineer for a fintech startup (now DevOps Training Architect II at Linux Academy), we’ll see exactly why serverless is starting to play such an important role the future of infrastructure.


Who am I?

My name is Chad Crowell and I am a DevOps Training Architect here at Linux Academy. In my previous role, I was a DevOps Engineer working for a fintech startup in Austin, Texas. I have been working in AWS for about three years now, and absolutely love the functionality and versatility of the platform. At the startup I worked for, we chose AWS for its high availability, fault tolerance, scalability, and elasticity. We consistently had 11 nines of uptime and found this, along with the performance, to make a positive impact for our customers and our company as a whole. We were spread across three different regions, so this weighed heavily on our profitability, being a financial software company.

What do I use AWS Lambda for?

We came about using this particular Lambda function within our environment in order to save costs. We built additional failover capability with load balancers in our environment so that when the number of users rapidly increased, we could provide additional compute resources.

During off hours, as most of the customers there are banks, therefore, following banking hours, activity is stagnant at best. As a result, we could shut down a majority of our instances due to this reduction of traffic. We saved about $2,000 per month on average and it allowed us to complete updates to our core software in a systematic way. We were still running in the free-tier for just Lambda, so it absolutely made sense from a business and cost perspective to do this.

For additional information on the cost structure and EC2 instance types, see the Amazon Elastic Compute Cloud (EC2) Instance Pricing. Amazon even offers a simple calculator for determining what your costs will be.

What is AWS Lambda?

Lambda is code that runs without complex administration against all or some of your AWS applications and/or backend services. You are only charged for the compute at the time your Lambda function runs, so it also can be extremely economical, especially if you are running thousands of lines of code in a single function.

It’s just code, and that’s it. There’s no need to provision or manage servers, which eliminates cost and complexity. This serverless concept is believed to replace most of what EC2 instances do in the future, as containers and serverless concepts become more commonplace.

The reason is because Lambda will control those services for you. No need to worry about provisioning adequate CPU or RAM when Lambda can do all of that for you, and best of all, you only pay for what you use–nothing more, nothing less. The supported languages for Lambda include Python, C#, Node.js and Java (as of the date of this publication).

Lambda Pricing

The pricing for the compute to run your Lambda function is almost nothing, and many times cheaper than even a t2.micro instance (the smallest EC2 instance). The first 1 million requests per month are free and it’s 20 cents per 1 million requests after that.

Creating a Lambda Function

In this example, we are going to run a python script to an EC2 instance. The reason we would want to stop an instance is for cost savings. As long as you are not running your instance, you are saving on compute, storage and memory utilization fees. For our organization, this ads up to a savings of over $2k per month. By turning all of our instances (130 total m4.large) off during non business hours (7 hours total), we are able to save $91.00 per day and $2,730.00 for the month.

This example of a Lambda function that I will go through in the following guide will not cost you anything. This means that if you set this up just as this guide instructs, you will not incur any charges and you will remain on the free tier. That being said, I am not responsible for any charges you may incur from Amazon Web Services, so please take careful consideration when creating any services in AWS, as they may have associated cost. To be safe, please review the official Amazon pricing details here.

Overview

This is a very short Lambda function, with only 17 lines of code. This will, however, demonstrate the ease of setup and the automation capabilities of Lambda. It could also open up some opportunity for continued exploration.

For those that want to explore more advanced configurations, please visit Linux Academy, where you can learn more about Lambda and other AWS services.

1. Log into the AWS web console.

2. Click on Services > Lambda under EC2:

Select Lambda under the EC2 Service menu

3. Open Lambda and click Create a function:

Select Create a Function

4. Click Author from scratch:

Select Author from Scratch

5. Choose a trigger by clicking the dotted lined square next to the Lambda icon:

Click the dotted line next to the Lambda icon

Then select Cloudwatch Events from the list:

Select CloudWatch Events

6. Select Create a new rule from the drop-down menu and give it a name (i.e. stop2300). Select Schedule expression and enter cron(0 23 ? * MON-FRI *)

Create a new CloudWatch rule

7. Select Enable trigger to turn on the event as soon as the function is created:

Select Enable Trigger

8. Give the function a name (i.e. myStopScript) and select “Python 2.7” as the runtime language:

Configure your function

9. Type the following code into your code block, substituting your region and your instance name:


Import boto3
# Region
Region = 'us-east-1'
# Instance, format: ['X-XXXXXXXX', 'X-XXXXXXXX']
instance = ['i-c6e30613']
def lambda_handler(event, context)
ec2 = boto3.client('ec2', region_name=region)
ec2.stop_instances(InstanceIds=instances)
print 'Stopped instance: ' + str(instances)

Enter the code for your Lambda function
10.  Select Create new role from template(s) from the drop down menu and enter a role name (i.e. lambdaRole):

Configure your Lambda role

11. Review the configuration details and select Create function. Click Next.

Review your settings

Create your Lambda function

12. Test your function by clicking Test:

Test your function

13. Use the Hello World event template, which will return a “null” result but will still accurately allow your function to succeed.

Use the Hello World template

Summary

Overall, we saved a ton of time configuring instances, installing packages and running code. By using Lambda, we were able to run our code instantly without having to configure anything or worry about resource constraints, as the service figures all of that out for us automatically. We easily just cut our deployment time in half, not to mention being able to test in-line.

The features of Lambda will keep extending and becoming more robust. Serverless concepts are the future and you will see containers replacing a lot of functionality, not only within AWS but within DevOps as a whole.

If you enjoyed this post, be sure to follow me on social media for more great content:

Twitter

Facebook

LinkedIn


Don’t forget to check out the new AWS online training content we launched in July!

AWS Online Training

The post Use AWS Lambda to Stop EC2 Instances appeared first on Linux Academy Blog.

You might also like
Leave A Reply

Your email address will not be published.