#!/usr/bin/python
import os
import json
import boto3
#python script to turn off the list of vms using lambda on daily/hourly basis
'''
event = {
"topic_arn": "arn:aws:sns:ap-southeast-1:aws-account_id:sns_topic",
"instance_id": "i-0fbaf00d222f6f765",
"action": "stop",
"region": "ap-southeast-1"
}
'''
#arguments can be passed through cloudwatch event which triggers lambda function or through lambda environment variables
def lambda_handler(event, context):
topic_arn = event['topic_arn']
instance_id = event['instance_id']
action = event['action']
region = event['region']
subject = instance_id
ec2_client = boto3.client('ec2')
sns_client = boto3.client('sns')
message = { "topic_arn" : topic_arn, "instance" : instance_id }
def stop_instance(instance_id):
stop_instance = ec2_client.stop_instances(InstanceIds=[instance_id,],Force=True)
message['status'] = 'stopped'
send_notification(topic_arn, subject, message)
return message
def start_instance(instance_id):
start_instance = ec2_client.start_instances(InstanceIds=[instance_id,])
message['status'] = 'started'
send_notification(topic_arn, subject, message)
return message
def send_notification(topic_arn, subject, message):
publish = sns_client.publish( TopicArn=topic_arn, \
Message=json.dumps(message), \
Subject=subject \
)
if action == 'stop':
return(stop_instance(instance_id))
else:
return(start_instance(instance_id))