More than 1 year has passed since last update.

【AWS】クラウド時代のバックアップ管理術  ~tagを活用したsnapshotの世代管理~
python botoを使って行うようにしたスクリプト

# coding: utf-8

import boto.ec2

region = 'ap-northeast-1'
aws_access_key = ''
aws_secret_key = ''

ec2 = boto.ec2.connect_to_region(region, aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key)

# タグ'backup'が'ON'のEC2インスタンスをバックアップ対象とする
instances = [i for r in ec2.get_all_instances(filters={'tag-key':'backup', 'tag-value':'ON'}) for i in r.instances]

for instance in instances:
  print "backup instance: %s" %

  # バックアップ世代数を、instanceのタグ'generation'から取得
  generation = int(instance.tags.get('generation'))
  print "backup generation: %s" % generation

  volumes = ec2.get_all_volumes(filters={'attachment.instance-id':})

  for v in volumes:
    # 新しいsnapshotを作成する
    print "create snapshot: %s" %
    v.create_snapshot(description='snapshot: ' +

    # start_timeの降順で並び替え、古い世代のsnapshotを削除する
    snaps = v.snapshots()
    sorted_snaps = sorted(snaps, key=lambda snap: snap.start_time, reverse=True)
    for i, snap in enumerate(sorted_snaps):
      if i >= generation:
        print "delete snapshot: %s" %
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account log in.