· 8 years ago · Jan 03, 2018, 10:14 AM
1import boto3
2from datetime import datetime, timedelta
3
4Date_UTC = datetime.utcnow() # Current date and time in UTC
5Date = datetime.now() # Current date and time
6Delta = Date_UTC - timedelta(days=3) # Retention period for snapshots
7
8snapshots_list = [] # Deleted snapshots list
9
10AccessKey = "" # Access Key to Amazon AWS
11SecretKey = "" # Secret Key to Amazon AWS
12
13ec2 = boto3.resource('ec2') # EC2 resource
14
15client_ec2 = boto3.client( # EC2 client
16 'ec2',
17 aws_access_key_id = AccessKey,
18 aws_secret_access_key = SecretKey,
19 region_name='eu-central-1')
20
21VM_Volume = client_ec2.describe_volumes() # Get all EC2 volumes
22
23all_snapshots = client_ec2.describe_snapshots(OwnerIds=['243285718310']) # Get all snapshots
24
25for snapshot_task in all_snapshots['Snapshots']:
26
27 snapshot_time = snapshot_task['StartTime'].replace(tzinfo=None) # Get snapshot creation time
28
29 snapshot = ec2.Snapshot(snapshot_task['SnapshotId']) # Get snapshot
30
31 if snapshot_time < Delta: # Deleting of all snapshots that older of retention period
32 snapshots_list.append(snapshot_task['SnapshotId']) # Add deleted snapshot to list
33 snapshot.delete()
34
35 else:
36 continue
37
38
39if snapshots_list: # Print output if deleted snapshots exist
40 print("Below snapshots was deleted:\n\n%s" % snapshots_list)
41
42for volume in VM_Volume['Volumes']: # Iterate through volumes
43
44 for x in volume['Attachments']:
45
46 # Create snapshot and add description
47 create_snapshot = ec2.create_snapshot(VolumeId = x['VolumeId'], Description = "Backup date: %s" % Date.strftime("%Y-%m-%d %H:%M:%S"))
48 # Tag snapshot with EC2 vm name
49 create_snapshot.create_tags(Tags = [{"Key": "Name", "Value": volume['Tags'][0]['Value']}])
50
51print("\nSnapshot creation task completed!")