Skip to content

Instantly share code, notes, and snippets.

@jamil666
Created December 28, 2017 12:31
Show Gist options
  • Save jamil666/d1fd626f56a8c2a31abed52d771351c2 to your computer and use it in GitHub Desktop.
Save jamil666/d1fd626f56a8c2a31abed52d771351c2 to your computer and use it in GitHub Desktop.
Amazon_EC2_Create_Snapshot
import boto3
from datetime import datetime, timedelta
Date_UTC = datetime.utcnow() # Current date and time in UTC
Date = datetime.now() # Current date and time
Delta = Date_UTC - timedelta(days=3) # Retention period for snapshots
snapshots_list = [] # Deleted snapshots list
AccessKey = "" # Access Key to Amazon AWS
SecretKey = "" # Secret Key to Amazon AWS
ec2 = boto3.resource('ec2') # EC2 resource
client_ec2 = boto3.client( # EC2 client
'ec2',
aws_access_key_id = AccessKey,
aws_secret_access_key = SecretKey,
region_name='eu-central-1')
VM_Volume = client_ec2.describe_volumes() # Get all EC2 volumes
all_snapshots = client_ec2.describe_snapshots(OwnerIds=['243285718310']) # Get all snapshots
for snapshot_task in all_snapshots['Snapshots']:
snapshot_time = snapshot_task['StartTime'].replace(tzinfo=None) # Get snapshot creation time
snapshot = ec2.Snapshot(snapshot_task['SnapshotId']) # Get snapshot
if snapshot_time < Delta: # Deleting of all snapshots that older of retention period
snapshots_list.append(snapshot_task['SnapshotId']) # Add deleted snapshot to list
snapshot.delete()
else:
continue
if snapshots_list: # Print output if deleted snapshots exist
print("Below snapshots was deleted:\n\n%s" % snapshots_list)
for volume in VM_Volume['Volumes']: # Iterate through volumes
for x in volume['Attachments']:
# Create snapshot and add description
create_snapshot = ec2.create_snapshot(VolumeId = x['VolumeId'], Description = "Backup date: %s" % Date.strftime("%Y-%m-%d %H:%M:%S"))
# Tag snapshot with EC2 vm name
create_snapshot.create_tags(Tags = [{"Key": "Name", "Value": volume['Tags'][0]['Value']}])
print("\nSnapshot creation task completed!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment