|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# |
| 3 | +# 特定のタグを含むEBSボリュームのスナップショットを作成する。 |
| 4 | +# Python 3.6 |
| 5 | +# |
| 6 | +# (参考) |
| 7 | +# https://qiita.com/HorieH/items/66bb68d12bd8fdbbd076 |
| 8 | +# https://inaba-serverdesign.jp/blog/20180330/aws_ec2_create_snapshot_lambda.html |
| 9 | +# EBSボリュームが存在するリージョンでLambda関数を作成すること。 |
| 10 | +# |
| 11 | +# 対象とするボリュームのタグで、 |
| 12 | +# Key: <TAGKEYの文字列>, Value: <保存世代数> |
| 13 | +# を設定すること。 |
| 14 | +# |
| 15 | +TAGKEY = 'Backup-Generation' |
| 16 | + |
| 17 | +import boto3 |
| 18 | +import collections |
| 19 | +import time |
| 20 | +from datetime import datetime as dt |
| 21 | + |
| 22 | +from botocore.client import ClientError |
| 23 | +import os |
| 24 | + |
| 25 | +client = boto3.client('ec2', os.environ['AWS_REGION']) |
| 26 | + |
| 27 | +def lambda_handler(event, context): |
| 28 | + descriptions = create_snapshots() |
| 29 | + delete_old_snapshots(descriptions) |
| 30 | + |
| 31 | +def create_snapshots(): |
| 32 | + volumes = get_volumes([TAGKEY]) |
| 33 | + |
| 34 | + descriptions = {} |
| 35 | + |
| 36 | + for v in volumes: |
| 37 | + tags = { t['Key']: t['Value'] for t in v['Tags'] } |
| 38 | + generation = int( tags.get(TAGKEY, 0) ) |
| 39 | + |
| 40 | + if generation < 1: |
| 41 | + continue |
| 42 | + |
| 43 | + volume_id = v['VolumeId'] |
| 44 | + description = volume_id if tags.get('Name') is '' else '%s(%s)' % (volume_id, tags['Name']) |
| 45 | + description = 'Auto Snapshot ' + description |
| 46 | + snapshot = _create_snapshot(volume_id, description) |
| 47 | + snapshot_id = snapshot['SnapshotId'] |
| 48 | + snapshot_name = get_snapshot_name(volume_id) |
| 49 | + print(snapshot_name) |
| 50 | + _create_tags(snapshot_id,snapshot_name) |
| 51 | + print('create snapshot %s(%s)' % (snapshot['SnapshotId'], description)) |
| 52 | + |
| 53 | + descriptions[description] = generation |
| 54 | + |
| 55 | + return descriptions |
| 56 | + |
| 57 | +def get_volumes(tag_names): |
| 58 | + volumes = client.describe_volumes( |
| 59 | + Filters=[ |
| 60 | + { |
| 61 | + 'Name': 'tag-key', |
| 62 | + 'Values': tag_names |
| 63 | + } |
| 64 | + ] |
| 65 | + )['Volumes'] |
| 66 | + |
| 67 | + return volumes |
| 68 | + |
| 69 | +def delete_old_snapshots(descriptions): |
| 70 | + snapshots_descriptions = get_snapshots_descriptions(list(descriptions.keys())) |
| 71 | + |
| 72 | + for description, snapshots in snapshots_descriptions.items(): |
| 73 | + delete_count = len(snapshots) - descriptions[description] |
| 74 | + |
| 75 | + if delete_count <= 0: |
| 76 | + continue |
| 77 | + |
| 78 | + snapshots.sort(key=lambda x:x['StartTime']) |
| 79 | + |
| 80 | + old_snapshots = snapshots[0:delete_count] |
| 81 | + |
| 82 | + for s in old_snapshots: |
| 83 | + _delete_snapshot(s['SnapshotId']) |
| 84 | + print('delete snapshot %s(%s)' % (s['SnapshotId'], s['Description'])) |
| 85 | + |
| 86 | +def get_snapshots_descriptions(descriptions): |
| 87 | + snapshots = client.describe_snapshots( |
| 88 | + Filters=[ |
| 89 | + { |
| 90 | + 'Name': 'description', |
| 91 | + 'Values': descriptions, |
| 92 | + } |
| 93 | + ] |
| 94 | + )['Snapshots'] |
| 95 | + |
| 96 | + groups = collections.defaultdict(lambda: []) |
| 97 | + { groups[ s['Description'] ].append(s) for s in snapshots } |
| 98 | + |
| 99 | + return groups |
| 100 | + |
| 101 | +def _create_snapshot(id, description): |
| 102 | + for i in range(1, 3): |
| 103 | + try: |
| 104 | + return client.create_snapshot(VolumeId=id,Description=description) |
| 105 | + except ClientError as e: |
| 106 | + print(str(e)) |
| 107 | + time.sleep(1) |
| 108 | + raise Exception('cannot create snapshot ' + description) |
| 109 | + |
| 110 | +def _delete_snapshot(id): |
| 111 | + for i in range(1, 3): |
| 112 | + try: |
| 113 | + return client.delete_snapshot(SnapshotId=id) |
| 114 | + except ClientError as e: |
| 115 | + print(str(e)) |
| 116 | + if e.response['Error']['Code'] == 'InvalidSnapshot.InUse': |
| 117 | + return; |
| 118 | + time.sleep(1) |
| 119 | + raise Exception('cannot delete snapshot ' + id) |
| 120 | + |
| 121 | +def _create_tags(id,name): |
| 122 | + response = client.create_tags( |
| 123 | + DryRun=False, |
| 124 | + Resources=[ |
| 125 | + id , |
| 126 | + ], |
| 127 | + Tags=[ |
| 128 | + { |
| 129 | + 'Key': 'Name', |
| 130 | + 'Value': name |
| 131 | + }, |
| 132 | + ] |
| 133 | + ) |
| 134 | +def get_snapshot_name(id): |
| 135 | + exec_time = dt.now().strftime('%Y%m%d') |
| 136 | + response = 'Seven Batch Add Volume_' + exec_time |
| 137 | + print(response) |
| 138 | + return response |
| 139 | +# EOF |
0 commit comments