Skip to content

Instantly share code, notes, and snippets.

@bngsudheer
Last active October 22, 2019 01:26
Show Gist options
  • Save bngsudheer/2a934531727911354915db14abaa20c0 to your computer and use it in GitHub Desktop.
Save bngsudheer/2a934531727911354915db14abaa20c0 to your computer and use it in GitHub Desktop.
AWS Lambda function to start and stop ec2 instances at designated schedules
# Copyright: Sudheera Satyanarayana. 2019.
# License. Apache 2.
# You need 3 AWS components to get this to work
# 1. DynamoDB Table 2. Lambda function 3. AWS CloudWatch Event Rule that triggers the Lambda function with specific inputs
# Following code is the lambda function
# When you create the lambda function, create two environment variables named `region` and `table_name`
# `region` is your AWS region
# `table_name` is the DynamoDB table
# Assign an IAM role with permissions to start/stop EC2 instances, read from DynamoDB table and write to CloudWatch logs
# The DynamoDB table should have three columns a) instance_id (string) b) start_morining(Boolean) c) stop_evening(Boolean)
# Configure two CloudWatch Event Rules. a) to start instances with input {"action": "start"} b) to stop instances with input {"action": "stop"}
# Message me on Github: @bngsudheer or reach out to me on TechChorus.net if you need help with this
import os
import json
import decimal
import boto3
from boto3.dynamodb.conditions import Key, Attr
# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
if o % 1 > 0:
return float(o)
else:
return int(o)
return super(DecimalEncoder, self).default(o)
def lambda_handler(event, context):
region = os.environ.get("region", "us-east-1")
dynamodb = boto3.resource('dynamodb', region_name=region)
table_name = os.environ.get("table_name", "ec2_schedules")
table = dynamodb.Table(table_name)
print("Fetching items from table {}".format(table_name))
response = table.scan()
ec2 = boto3.client('ec2', region_name=region)
instance_ids = []
for i in response['Items']:
instance_ids.append(i['instance_id'])
if not instance_ids:
return {
'statusCode': 200,
'body': json.dumps('No instance found')
}
if event["action"] == "start":
ec2.start_instances(InstanceIds=instance_ids)
elif event["action"] == "stop":
ec2.stop_instances(InstanceIds=instance_ids)
return {
'statusCode': 200,
'body': json.dumps('Finished instance action {} for instances = {}'.format(event["action"], instance_ids))
}
# Code to insert into DynamoDB table:
# import boto3
# import json
# import decimal
#
# dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
# table = dynamodb.Table('ec2_schedules')
#
# response = table.put_item(
# Item={
# 'instance_id': 'i-xxxxxxxxx',
# }
# )
# print(response)
# response = table.put_item(
# Item={
# 'instance_id': 'i-xxxxx'
# }
# )
# print(response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment