Created
November 23, 2020 10:00
-
-
Save yuklia/e98710d1fa99e61feb5f25e7cb7fc555 to your computer and use it in GitHub Desktop.
Create ebs snapshots with retention time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json, boto3 | |
from datetime import datetime | |
from tag_name import TagName | |
''' | |
ebs_backups = EBSBackup() | |
ebs_backups.create_snapshots() | |
''' | |
class EBSBackup(object): | |
RETENTION_IN_DAYS = 2 | |
RARIS_REGION = 'eu-west-3' | |
def __init__(self, region): | |
self.ec2 = boto3.client('ec2', region) | |
def __get_retention_tag_value(self): | |
return "{0} days".format(self.RETENTION_IN_DAYS) | |
def __get_volumes_for_backup(self): | |
ebs_info = self.ec2.describe_volumes(Filters=[{'Name': 'tag-key', 'Values': ['backup', 'True']}]) | |
if not ebs_info: | |
print('ec2.describe_volumes is empty list') | |
volumes = ebs_info['Volumes'] | |
if not volumes: | |
print('No volumes were found.') | |
return volumes | |
def __create_snapshot(self, volume={}): | |
snapshot = self.ec2.create_snapshot( | |
VolumeId=volume['VolumeId'], | |
Description="Periodical backup for ebs: " + volume['VolumeId'] | |
) | |
if not snapshot: | |
print('Can\'t create snapshot for volume {0}'.format(volume['VolumeId'])) | |
return snapshot | |
def __add_retention_time_to_snapshot(self, snapshot={}, volume={}): | |
snap_id = snapshot["SnapshotId"] | |
self.ec2.create_tags(Resources=[snap_id],Tags=[{'Key': 'Retention', 'Value': self.__get_retention_tag_value()}]) | |
print('Tag:Retention "{0}" for snap_id {1} is created.'.format(self.__get_retention_tag_value(), snap_id)) | |
def __add_name_to_snapshot(self, snapshot={}, volume={}): | |
snap_id = snapshot["SnapshotId"] | |
tag_name = TagName(tags=volume['Tags']) | |
volume_name = tag_name.get_name_value() | |
self.ec2.create_tags(Resources=[snap_id],Tags=[{'Key': 'Name', 'Value': volume_name }]) | |
print('Tag:Name "{0}" for snap_id {1} is created.'.format(volume_name, snap_id)) | |
def create_snapshots(self): | |
volumes = self.__get_volumes_for_backup() | |
for volume in volumes: | |
snapshot = self.__create_snapshot(volume) | |
self.__add_name_to_snapshot(snapshot=snapshot, volume=volume) | |
self.__add_retention_time_to_snapshot(snapshot=snapshot, volume=volume) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment