miércoles, 22 de septiembre de 2021

AWS: script python para crear snapshots y rotarlos



script en python para crear snapshots y rotarlos en AWS.



A continuación explicaré como crear snapshots en AWS usando un script en python, que a su vez rotará los snapshots, todo ello usando AWS cli en Linux.

Crear un cron que cree snapshots cada *:

[ec2-user@ip-10-5-0-143 ~]$ echo "* * * * * aws ec2 create-snapshot --volume-id vol-0b2efa7e024e758e5 2>&1 >> /tmp/cronlog" > cronjob [ec2-user@ip-10-5-0-143 ~]$ crontab cronjob

Miramos qué snapshots existen en este momento:

[ec2-user@ip-10-5-0-143 ~]$ aws ec2 describe-snapshots --filters "Name=volume-id,Values=vol-0b2efa7e024e758e5" { "Snapshots": [ { "Description": "", "Encrypted": false, "VolumeId": "vol-0b2efa7e024e758e5", "State": "pending", "VolumeSize": 8, "StartTime": "2020-06-17T10:50:02.036Z", "Progress": "99%", "OwnerId": "077455710323", "SnapshotId": "snap-0c9062daba8a9f4f7" }, { "Description": "", "Encrypted": false, "VolumeId": "vol-0b2efa7e024e758e5", "State": "completed", "VolumeSize": 8, "StartTime": "2020-06-17T10:45:11.200Z", "Progress": "100%", "OwnerId": "077455710323", "SnapshotId": "snap-0f2af28035ea778e5" }, { "Description": "", "Encrypted": false, "VolumeId": "vol-0b2efa7e024e758e5", "State": "completed", "VolumeSize": 8, "StartTime": "2020-06-17T10:49:02.082Z", "Progress": "100%", "OwnerId": "077455710323", "SnapshotId": "snap-0870e6eba7a6cc337" } ] }

Paramos crontab:

[ec2-user@ip-10-5-0-143 ~]$ crontab -r

Script para eliminar snapshots excepto 2:

[ec2-user@ip-10-5-0-143 ~]$ more snapshotter.py #!/usr/bin/env python import boto3 MAX_SNAPSHOTS = 2 # Number of snapshots to keep # Create the EC2 resource ec2 = boto3.resource('ec2') # Get a list of all volumes volume_iterator = ec2.volumes.all() # Create a snapshot of each volume for v in volume_iterator: v.create_snapshot() # Too many snapshots? snapshots = list(v.snapshots.all()) if len(snapshots) > MAX_SNAPSHOTS: # Delete oldest snapshots, but keep MAX_SNAPSHOTS available snap_sorted = sorted([(s.id, s.start_time, s) for s in snapshots], key=lambd a k: k[1]) for s in snap_sorted[:-MAX_SNAPSHOTS]: print "Deleting snapshot", s[0] s[2].delete()

Miramos cuantos snapshots hay:

[ec2-user@ip-10-5-0-143 ~]$ aws ec2 describe-snapshots --filters "Name=volume-id, Values=vol-0b2efa7e024e758e5" --query 'Snapshots[*].SnapshotId' [ "snap-0c9062daba8a9f4f7", "snap-0f2af28035ea778e5", "snap-0870e6eba7a6cc337" ]

Ejecutamos el script:

[ec2-user@ip-10-5-0-143 ~]$ python snapshotter.py Deleting snapshot snap-0f2af28035ea778e5 Deleting snapshot snap-0870e6eba7a6cc337

Miramos cuantos snapshos quedan:

[ec2-user@ip-10-5-0-143 ~]$ aws ec2 describe-snapshots --filters "Name=volume-id, Values=vol-0b2efa7e024e758e5" --query 'Snapshots[*].SnapshotId' [ "snap-0c9062daba8a9f4f7", "snap-0c87c81530f2f06c3" ]
0

0 comentarios:

Publicar un comentario