Automatically Starting and Stopping AWS EC2 instances to save cost
Most of the time, your EC2 servers don’t need to run 24/7 and automatically starting and stopping your EC2 servers can save you a considerable amount.
I know that you can buy Reserved Instances, but if your server instances are unpredictable, starting and stopping them may be a good option.
In my solution, I have will tag my server with the value AutoOff=True to indicate weather to automatically shutdown the instance at the given time.
You could extend the value of this Tag to fit your requirements
The Code
To Implement the starting and stopping mechanism, a Lambda function in Python was coded.
import boto3
import logginglogger = logging.getLogger()
logger.setLevel(logging.INFO)def startstopinstances(Action):
ec2 = boto3.resource('ec2')if Action == 'stop':
filters = [
{
'Name': 'tag:AutoOff',
'Values': ['True']
},
{
'Name': 'instance-state-name',
'Values': ['running']
}
]
else :
filters = [
{
'Name': 'tag:AutoOff',
'Values': ['True']
},
{
'Name': 'instance-state-name',
'Values': ['stopped']
}
]
instances = ec2.instances.filter(Filters=filters)
instancesFound = 0
for oneInstance in instances:
logger.info('%s Instance ID: %s', Action, oneInstance.id)
instancesFound = 1
if instancesFound == 0:
logger.info('No Instances found to %s....', Action)
else:
#Start/Stop instances that are tagged AutoOff=True
if Action == 'stop':
instances.stop()
else :
instances.start()
def lambda_handler(event, context):
logger.info('%s instances...', event['action'])
startstopinstances(event['action'])
The Needed Role
The Lambda function needs an Execution role that will enable him to start and stop EC2 Instances
I created a Role called lambda_start_stop_ec2 and attached the builtin policy AmazonEC2FullAccess.
Testing
To test my lambda function, I created a Test event that passed the stop value as the action argument.
The same test event was created for Stopping the instances
Scheduling
I hope your test succeeded and you can now create a CloudWatch trigger that will call the lambda function at predefined times.
I created two triggers that will call the lambda function with the defined arguments.