Last active
August 29, 2018 17:37
-
-
Save gotraveltoworld/862890e21e235e0152779104221339b8 to your computer and use it in GitHub Desktop.
To use the python for auto-snapshot.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import datetime | |
from datetime import timezone | |
import boto3 # Import from basic library (base on aws lambda) | |
""" | |
os.environ: { | |
'aws_access_key_id', <= aws's id. | |
'aws_secret_access_key', <= aws's key. | |
'retention_days', <= this is a retention. | |
'region_names' <= this is your own region. | |
} | |
""" | |
def lambda_handler(event=None, context=None): | |
print('AWS snapshot backups starting at {0}'.format( | |
datetime.datetime.now(timezone.utc) | |
) | |
) | |
# Get all regin names by string(ap-xxx,us-xxx). | |
regions = map(lambda x: x.strip(), os.environ['region_names'].split(',')) | |
for region in regions: | |
ec2 = boto3.resource( | |
'ec2', | |
aws_access_key_id=os.environ['aws_access_key_id'], | |
aws_secret_access_key=os.environ['aws_secret_access_key'], | |
region_name=region | |
) | |
instances = ec2.instances.filter( | |
Filters=[{'Name': 'instance-state-name', 'Values': ['running']}] | |
) | |
# If this instance has a pair of '{snapshot: true}', and then to create the snapshot. | |
filter_objects = [ | |
{ | |
'instance_id': instance.id, | |
'instance_name': [ | |
t.get('Value') for t in instance.tags if t.get('Key') == 'Name' | |
][0] | |
} for instance in instances | |
if instance.tags | |
for tag in instance.tags | |
if tag.get('Key') == 'snapshot' and tag.get('Value') == 'true' | |
] | |
for instance in filter_objects: | |
for volume in ec2.volumes.filter( | |
Filters=[{'Name': 'attachment.instance-id', 'Values': [instance['instance_id']]}]): | |
description = '{0};{1};{2}'.format( | |
instance['instance_name'], | |
volume.volume_id, | |
datetime.datetime.now().strftime("%Y%m%d") | |
) | |
# create ebs snaphost | |
try: | |
checks = [ | |
snapshot.description for snapshot in volume.snapshots.all() | |
if snapshot.description | |
] | |
if description not in checks: | |
# Create new snapshot. | |
snapshot_name = 'Auto_Backup:{0}'.format(instance['instance_name']) | |
if volume.create_snapshot( | |
TagSpecifications=[ | |
{ | |
'ResourceType': 'snapshot', | |
'Tags': [ | |
{ | |
'Key': 'Name', | |
'Value': snapshot_name | |
} | |
] | |
} | |
], | |
VolumeId=volume.volume_id, | |
Description=description | |
): | |
print("Snapshot created with description {0}".format(description)) | |
else: | |
print('The snaphost does exist, {0}'.format(description)) | |
except Exception as e: | |
print("Create the snapshot error {0}:".format(e)) | |
pass | |
# Delete over-expired snapshots. | |
try: | |
for snapshot in volume.snapshots.all(): | |
# Default retention's day is 30. | |
retention_days = int(os.environ.get('retention_days', 30)) | |
now_time = datetime.datetime.now(timezone.utc) | |
time_checking = (now_time - snapshot.start_time.replace(tzinfo=timezone.utc) > datetime.timedelta(days=retention_days)) | |
if ( | |
snapshot.tags and | |
time_checking and | |
[ | |
t.get('Value') for t in snapshot.tags | |
if t.get('Key') == 'Name' and t.get('Value').startswith('Auto_Backup') | |
] | |
): | |
print('Deleting snapshot [{0} - {1}]'.format(snapshot.snapshot_id, snapshot.description)) | |
snapshot.delete() | |
except Exception as e: | |
print("Delete the snapshot error {0}:".format(e)) | |
pass | |
print( | |
'AWS snapshot backups completed at region:{0}; {1}'.format( | |
region, datetime.datetime.now() | |
) | |
) | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment