AWS Lambda is Amazon’s serverless compute service. You can run your code on it without having to manage servers or even containers. It will automatically scale depending on how much work you feed into it. And it build event-driven functions for easy communication between decoupled services. Reduce costs by running applications during times of peak demand i.e you need to pay only for the time taken to execute the code. The key features of Lambda function are :
- Run code without provisioning or managing infrastructure. Simply write and upload code as a .zip file or container image
- Automatically respond to code execution requests at any scale, from a dozen events per day to hundreds of thousands per second.
- Save costs by paying only for the compute time you use by per-millisecond instead of provisioning infrastructure upfront for peak capacity.
- Optimize code execution time and performance with the right function memory size.
First we will be creating a lambda function to stop/start testing instance in order to reduce cost. Then we will create a python code to stop, start instance and upload it to Lambda. Now we will apply a trigger on lambda function using AWS cloudwatch events. We have crontab facility in AWS cloudwatch, so we schedule a cronjob to apply the trigger on lambda at the demanding time.
-
Boto module
# pip3 install boto3
- Python code to stop/start instance (stop.py, start.py)
An IAM role with "AmazonEC2FullAccess" premission is created to allow Lambda functions to call AWS services.
For that navigate to Lambda >> Functions >> create function - provide the Basic information, select the pre-created IAM role "ec2-stop-start" >> Create Function
The created lambda function interface will be as below :
Now replace the default code with our python code to stop the instance and click on the "Deploy" button to update/upload the code to the lambda fuction.
Now we will apply a trigger on Lambda function using the AWS Cloudwatch to run the code on our time demanded. We have crontab feature in AWS Cloudwatch to schedule a cronjob.
Navigate to AWS Cloudwatch >> Events >> Rule >> Create Rule
Select Cron Expression under Schedule and set a cronjob. Now set up Trigger by Adding Target for lambda function and select the precreated Lambda function "test-instance-stop"
On selecting the created rule we can see next 10 Trigger Dates listed
NOTE :: Follow the same proceedure to create a lambda function to start an instance by replacing a single line in the code "ec2.stop_instances(InstanceIds=[ instance_Id ])" to "ec2.start_instances(InstanceIds=[ instance_Id ])".
A lambda function is created to stop and start a testing instance during times of peak demand by reducing the cost.