Skip to content

Instantly share code, notes, and snippets.

@hetul99
Last active August 6, 2020 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hetul99/6268c2c2ce4fbd89b6e1a89ac6188363 to your computer and use it in GitHub Desktop.
Save hetul99/6268c2c2ce4fbd89b6e1a89ac6188363 to your computer and use it in GitHub Desktop.
This snapshot will keep on creating the snaps of EC2 instances having the TAGS as "backup"="true". But you have to schedule when to take snaps in the CloudWatch Event Rule. Also this will keep on creating the snap so REMEMBER to implement PruneSnapShots lambda function when you use this CreateSnapShot function to delete the snapshot created and …
from datetime import datetime
import boto3
def lambda_handler(event, context):
ec2_client = boto3.client('ec2')
regions = [region['RegionName']
for region in ec2_client.describe_regions()['Regions']]
for region in regions:
print('Instances in EC2 Region {0}:'.format(region))
ec2 = boto3.resource('ec2', region_name=region)
instances = ec2.instances.filter(
Filters=[ {'Name': 'tag:backup', 'Values': ['true']}
]
)
# ISO 8601 timestamp, i.e. 2019-01-31T14:01:58
timestamp = datetime.utcnow().replace(microsecond=0).isoformat()
for i in instances.all():
for v in i.volumes.all():
desc = 'Backup of {0}, volume {1}. created {2}'.format(i.id, v.id, timestamp)
print(desc)
snapshot = v.create_snapshot(Description=desc)
print("Created snapshot:", snapshot.id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment