Skip to content

Instantly share code, notes, and snippets.

@s2krish
Last active September 2, 2022 04:45
Show Gist options
  • Save s2krish/c53a44f521f2db30742fcc63ca1fd27f to your computer and use it in GitHub Desktop.
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 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()
@s2krish
Copy link
Author

s2krish commented Sep 2, 2022

This may not require as AWS has Life Cycle Policy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment