LoginSignup
1
1

More than 5 years have passed since last update.

EBS ボリュームの snapshot をとるスクリプト

Posted at

ちょっと kobito からの投稿テストを兼ねて。
EC2 は EBS ボリュームの snapshot 取っておけばバックアップになるので以前書いたスクリプト。

class AWSBackuper(object):
    def __init__(self, access_key, secret_key, region="ap-northeast-1"):
        self.access_key = access_key
        self.secret_key = secret_key
        self.region = region
        self.set_ec2connection()

    def set_ec2connection(self):
        self.ec2connection = boto.ec2.connect_to_region(self.region, aws_access_key_id=self.access_key, aws_secret_access_key=self.secret_key)

    def create_snapshot(self, volume_id, description=None):
        self.ec2connection.create_snapshot(volume_id, description)

    def rotate_snapshot(self, volume_id, num):
        snapshot = {}
        for x in self.ec2connection.get_all_snapshots():
            if(x.volume_id == volume_id):
                tmp = {x.id:x.start_time}
                snapshot.update(tmp)

        snapshot = sorted(snapshot.items(), key=lambda (k, v): (v, k), reverse=True)
        for i in range(int(num), len(snapshot)):
            try:
                self.ec2connection.delete_snapshot(snapshot[i][0])
            except:
                continue

    def add_tags_to_snapshot(self, volume_id):
        tags = self.ec2connection.get_all_volumes(volume_id)[0].tags

        for snapshot in self.ec2connection.get_all_snapshots():
            if(snapshot.volume_id == volume_id):
                for key, value in tags.items():
                    snapshot.add_tag(key, value)

if __name__ == '__main__':

    execfile(sys.argv[1])
    backuper = AWSBackuper(access_key, secret_key)

    for volume_id in volume_ids:
        backuper.create_snapshot(volume_id, 'auto backup')
        print "%s is backed up." % (volume_id)
        backuper.rotate_snapshot(volume_id, generation_limit)
        print "%s is rotated snapshots." % (volume_id)
        backuper.add_tags_to_snapshot(volume_id)
        print "%s is added tags." % (volume_id)

このスクリプトは config ファイルとなる python スクリプトを指定して起動する。

# your volume_ids 
access_key, secret_key = 'YOUR ACCESS KEY', 'YOUR SECRET KEY'
volume_ids = [
    'vol-target-id1',
    'vol-target-id2',
    'vol-target-id3',
]
generation_limit = 7

あとはこんなふうに起動するだけ

python ebs-backuper.py config.py
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1