6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AWSでebsのスナップショットを自動作成

Last updated at Posted at 2013-03-29

【AWS】クラウド時代のバックアップ管理術  ~tagを活用したsnapshotの世代管理~
http://shanon-tech.blogspot.jp/2013/02/awstagsnapshot.html
にある、タグを使ったスナップショット管理方式を参考に、
python botoを使って行うようにしたスクリプト

create_snapshot.rb
# 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.id

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

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

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

    # 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" % snap.id
        snap.delete()
6
6
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
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?