Save your money shutting down EC2 Instance with AWS Lambda!
As you know, when we create an AWS EC2 instance, we don’t use these instances all the time. For example, mostly developers use Jenkins work hours. So, we can shut down this instance. And turn it on automatically, when we start to work.
So, we can use lambda to make it right.
Go, Lambda > Functions > Create a Lambda Function
We will create a Lambda script using Python and boto3.
Create a Lambda script which name is “AutoOff”
import boto3 import logging ec2 = boto3.resource('ec2') def lambda_handler(event, context): filters = [{ 'Name': 'tag:AutoOff', 'Values': ['True'] }, { 'Name': 'instance-state-name', 'Values': ['running'] } ] instances = ec2.instances.filter(Filters=filters) RunningInstances = [instance.id for instance in instances] if len(RunningInstances) > 0: shuttingDown = ec2.instances.filter(InstanceIds=RunningInstances).stop() print shuttingDown
Create a Lambda script which name is “AutoOn”
import boto3 import logging ec2 = boto3.resource('ec2') def lambda_handler(event, context): filters = [{ 'Name': 'tag:AutoOff', 'Values': ['True'] }, { 'Name': 'instance-state-name', 'Values': ['stopped'] } ] instances = ec2.instances.filter(Filters=filters) StoppedInstances = [instance.id for instance in instances] if len(StoppedInstances) > 0: startingInstance = ec2.instances.filter(InstanceIds=StoppedInstances).start() print startingInstance
After, created these Lambda scripts. Now, we should add them event source to schedule when our instances will stop or start. Go, lambda script details, and click event sources.
Event Source Type: CloudWatch Events – Schedule
Rule name: Auto ON or OFF (its up to you)
Give your cron expression when you want to start/stop these instances.
Enable Event Source and save the event source.
Now, go your instances you want to do start/stop automatically. And add this tag.
Key: AutoOff
Value: True
Thats it!