Skip to content

Instantly share code, notes, and snippets.

@ratulbasak
Created April 5, 2018 11:45
Show Gist options
  • Save ratulbasak/0c6cba01b9d2dbc0701e581068400b27 to your computer and use it in GitHub Desktop.
Save ratulbasak/0c6cba01b9d2dbc0701e581068400b27 to your computer and use it in GitHub Desktop.
This script will stop instance and find instance by "Backup" tag, create snapshot of additional volume and then start the instance
import boto3
import collections
import datetime
import base64
import os
region = os.environ['aws_regions']
# aws_sns_arn = os.getenv('aws_sns_arn', None)
"""def send_to_sns(subject, message):
if aws_sns_arn is None:
return
print "Sending notification to: %s" % aws_sns_arn
client = boto3.client('sns')
response = client.publish(
TargetArn=aws_sns_arn,
Message=message,
Subject=subject)
if 'MessageId' in response:
print "Notification sent with message id: %s" % response['MessageId']
else:
print "Sending notification failed with response: %s" % str(response)"""
def lambda_handler(event, context):
print "Backing up instances in region: %s" % region
ec = boto3.client('ec2', region_name=region)
reservations = ec.describe_instances(
Filters=[{'Name': 'tag-key', 'Values': ['backup', 'Backup']},]
).get('Reservations', [])
instances = sum(
[
[i for i in r['Instances']]
for r in reservations
], [])
print "Found %d instances that need backing up in region %s" % (len(instances), region)
to_tag_mount_point = collections.defaultdict(list)
"""STOPPING INSTANCE FOR CREATING SNAPSHOT BACKUP """
for instance in instances:
INSTANCE_ID = instance['InstanceId']
print("STOPPING >>>> INSTANCE ID : " + INSTANCE_ID)
response = ec.stop_instances(
InstanceIds=[INSTANCE_ID]
)
waiter=ec.get_waiter('instance_stopped')
waiter.wait(InstanceIds=[INSTANCE_ID])
print("INSTANCE %s STOPPED" % INSTANCE_ID)
"""FINDING INSTANCE AND VOLUME THAT NEEDS TO BE BACKUP"""
try:
retention_days = [
int(t.get('Value')) for t in instance['Tags']
if t['Key'] == 'Retention'][0]
except IndexError:
retention_days = 7
try:
skip_volumes = [
str(t.get('Value')).split(',') for t in instance['Tags']
if t['Key'] == 'Skip_Backup_Volumes']
except Exception:
pass
from itertools import chain
skip_volumes_list = list(chain.from_iterable(skip_volumes))
for dev in instance['BlockDeviceMappings']:
if dev.get('Ebs', None) is None:
continue
vol_id = dev['Ebs']['VolumeId']
if vol_id in skip_volumes_list:
print "Volume %s is set to be skipped, not backing up" % (vol_id)
continue
dev_attachment = dev['DeviceName']
print "Found EBS volume %s on instance %s attached to %s" % (
vol_id, instance['InstanceId'], dev_attachment)
print(dev_attachment)
instance_name = ''
try:
instance_name = [ x['Value'] for x in instance['Tags'] if x['Key'] == 'Name' ][0]
except IndexError:
pass
"""CREATING SNAPSHOT BACKUP FROM INSTANCE VOLUME"""
if dev_attachment != '/dev/sda1':
snap = ec.create_snapshot(
VolumeId=vol_id,
Description='{} {}'.format(instance_name, instance['InstanceId'])
)
SNAP_ID = snap['SnapshotId']
to_tag_mount_point[vol_id].append(SNAP_ID)
ec.create_tags(
Resources=to_tag_mount_point[vol_id],
Tags=[
{'Key': 'Name', 'Value': dev_attachment},
]
)
print("CREATING SNAPSHOT....")
waiter = ec.get_waiter('snapshot_completed')
waiter.wait(SnapshotIds=[SNAP_ID])
print("SNAPSHOT %s is AVAILABLE" % SNAP_ID)
"""STARTING INSTANCE AFTER SNAPSHOT BACKUP CREATED"""
response = ec.start_instances(
InstanceIds=[INSTANCE_ID]
)
print("STARTING >>>>> INSTANCE ID : " + INSTANCE_ID)
waiter=ec.get_waiter('instance_running')
waiter.wait(InstanceIds=[INSTANCE_ID])
print("INSTANCE %s STARTED AFTER TAKING BACKUP" % INSTANCE_ID)
"""message = "{} instances have been backed up in region {}".format(len(instances), region)
send_to_sns('EBS Backups', message)"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment