Last active
September 2, 2022 04:45
-
-
Save s2krish/c53a44f521f2db30742fcc63ca1fd27f to your computer and use it in GitHub Desktop.
Automated backup of EC2 Volume for last seven days using AWS CloudWatch
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
''' | |
This is tiny script (self note) for automated back of AWS EC2 | |
1. Create Lambda function. Visit https://us-west-2.console.aws.amazon.com/lambda/home | |
2. Assigned right AIM role (should have sufficient privileges). Visit https://console.aws.amazon.com/iam/home?#/roles) | |
3. Set to schedule run from CloudWatch Event. Visit https://us-west-2.console.aws.amazon.com/cloudwatch/home | |
''' | |
import boto3 | |
import datetime | |
region ='region' | |
ec2 = boto3.resource('ec2' region) | |
client = boto3.client('ec2', region) | |
def describe_volumes(): | |
volumes = client.describe_volumes( | |
Filters=[ | |
{'Name': 'tag:Name', 'Values': ['VolumeName']}, | |
] | |
) | |
if len(volumes['Volumes']) >= 1: | |
volume_id = volumes['Volumes'][0]['Attachments'][0]['VolumeId'] | |
volume = ec2.Volume(volume_id) | |
snapshot = volume.create_snapshot(Description='PowrbotMainVolumeImageBackup') | |
now = datetime.datetime.utcnow() - datetime.timedelta(days=7) | |
for image in volume.snapshots.all(): | |
tnow = image.start_time.replace(tzinfo=None) | |
if image.description == 'AutoSnappVolumeImages' and now > tnow: | |
image.delete() | |
def lambda_handler(event, context): | |
describe_volumes() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This may not require as AWS has Life Cycle Policy