Skip to content
This repository was archived by the owner on Apr 23, 2020. It is now read-only.

Commit 6281afc

Browse files
author
Chris Machler
committed
Adding multi-region functionality issue #2.
1 parent d819d50 commit 6281afc

File tree

2 files changed

+87
-82
lines changed

2 files changed

+87
-82
lines changed

lambda-ebs-backup-cleanup.py

Lines changed: 30 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
import re
33
import datetime
44

5-
ec = boto3.client('ec2')
5+
regions = ['us-west-2','us-east-2']
6+
67
iam = boto3.client('iam')
78

89
"""
@@ -12,29 +13,31 @@
1213
"""
1314

1415
def lambda_handler(event, context):
15-
account_ids = list()
16-
try:
17-
"""
18-
You can replace this try/except by filling in `account_ids` yourself.
19-
Get your account ID with:
20-
> import boto3
21-
> iam = boto3.client('iam')
22-
> print iam.get_user()['User']['Arn'].split(':')[4]
23-
"""
24-
iam.get_user()
25-
except Exception as e:
26-
# use the exception message to get the account ID the function executes under
27-
account_ids.append(re.search(r'(arn:aws:sts::)([0-9]+)', str(e)).groups()[1])
28-
29-
30-
delete_on = datetime.date.today().strftime('%Y-%m-%d')
31-
filters = [
32-
{'Name': 'tag-key', 'Values': ['DeleteOn']},
33-
{'Name': 'tag-value', 'Values': [delete_on]},
34-
]
35-
snapshot_response = ec.describe_snapshots(OwnerIds=account_ids, Filters=filters)
36-
37-
38-
for snap in snapshot_response['Snapshots']:
39-
print "Deleting snapshot %s" % snap['SnapshotId']
40-
ec.delete_snapshot(SnapshotId=snap['SnapshotId'])
16+
for region in regions:
17+
ec = boto3.client('ec2', region_name=region)
18+
account_ids = list()
19+
try:
20+
"""
21+
You can replace this try/except by filling in `account_ids` yourself.
22+
Get your account ID with:
23+
> import boto3
24+
> iam = boto3.client('iam')
25+
> print iam.get_user()['User']['Arn'].split(':')[4]
26+
"""
27+
iam.get_user()
28+
except Exception as e:
29+
# use the exception message to get the account ID the function executes under
30+
account_ids.append(re.search(r'(arn:aws:sts::)([0-9]+)', str(e)).groups()[1])
31+
32+
33+
delete_on = datetime.date.today().strftime('%Y-%m-%d')
34+
filters = [
35+
{'Name': 'tag-key', 'Values': ['DeleteOn']},
36+
{'Name': 'tag-value', 'Values': [delete_on]},
37+
]
38+
snapshot_response = ec.describe_snapshots(OwnerIds=account_ids, Filters=filters)
39+
40+
41+
for snap in snapshot_response['Snapshots']:
42+
print "Deleting snapshot %s" % snap['SnapshotId']
43+
ec.delete_snapshot(SnapshotId=snap['SnapshotId'])

lambda-ebs-backup.py

Lines changed: 57 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -2,74 +2,76 @@
22
import collections
33
import datetime
44

5-
ec = boto3.client('ec2')
5+
regions = ['us-west-2','us-east-2']
66

77
def lambda_handler(event, context):
8-
reservations = ec.describe_instances(
9-
Filters=[
10-
{'Name': 'tag-key', 'Values': ['backup', 'Backup']},
11-
]
12-
).get(
13-
'Reservations', []
14-
)
8+
for region in regions:
9+
ec = boto3.client('ec2', region_name=region)
10+
reservations = ec.describe_instances(
11+
Filters=[
12+
{'Name': 'tag-key', 'Values': ['backup', 'Backup']},
13+
]
14+
).get(
15+
'Reservations', []
16+
)
1517

16-
instances = sum(
17-
[
18-
[i for i in r['Instances']]
19-
for r in reservations
20-
], [])
18+
instances = sum(
19+
[
20+
[i for i in r['Instances']]
21+
for r in reservations
22+
], [])
2123

22-
print "Found %d instances that need backing up" % len(instances)
24+
print "Found %d instances that need backing up" % len(instances)
2325

24-
to_tag_retention = collections.defaultdict(list)
25-
to_tag_mount_point = collections.defaultdict(list)
26+
to_tag_retention = collections.defaultdict(list)
27+
to_tag_mount_point = collections.defaultdict(list)
2628

27-
for instance in instances:
28-
try:
29-
retention_days = [
30-
int(t.get('Value')) for t in instance['Tags']
31-
if t['Key'] == 'Retention'][0]
32-
except IndexError:
33-
retention_days = 7
29+
for instance in instances:
30+
try:
31+
retention_days = [
32+
int(t.get('Value')) for t in instance['Tags']
33+
if t['Key'] == 'Retention'][0]
34+
except IndexError:
35+
retention_days = 7
3436

35-
for dev in instance['BlockDeviceMappings']:
36-
if dev.get('Ebs', None) is None:
37-
continue
38-
vol_id = dev['Ebs']['VolumeId']
39-
dev_attachment = dev['DeviceName']
40-
print "Found EBS volume %s on instance %s attached to %s" % (
41-
vol_id, instance['InstanceId'], dev_attachment)
37+
for dev in instance['BlockDeviceMappings']:
38+
if dev.get('Ebs', None) is None:
39+
continue
40+
vol_id = dev['Ebs']['VolumeId']
41+
dev_attachment = dev['DeviceName']
42+
print "Found EBS volume %s on instance %s attached to %s" % (
43+
vol_id, instance['InstanceId'], dev_attachment)
4244

43-
snap = ec.create_snapshot(
44-
VolumeId=vol_id,
45-
Description=instance['InstanceId'],
46-
)
45+
snap = ec.create_snapshot(
46+
VolumeId=vol_id,
47+
Description=instance['InstanceId'],
48+
)
4749

48-
to_tag_retention[retention_days].append(snap['SnapshotId'])
49-
to_tag_mount_point[vol_id].append(snap['SnapshotId'])
50+
to_tag_retention[retention_days].append(snap['SnapshotId'])
51+
to_tag_mount_point[vol_id].append(snap['SnapshotId'])
5052

5153

52-
print "Retaining snapshot %s of volume %s from instance %s for %d days" % (
53-
snap['SnapshotId'],
54-
vol_id,
55-
instance['InstanceId'],
56-
retention_days,
57-
)
54+
print "Retaining snapshot %s of volume %s from instance %s for %d days" % (
55+
snap['SnapshotId'],
56+
vol_id,
57+
instance['InstanceId'],
58+
retention_days,
59+
)
5860

61+
ec.create_tags(
62+
Resources=to_tag_mount_point[vol_id],
63+
Tags=[
64+
{'Key': 'Name', 'Value': dev_attachment},
65+
]
66+
)
67+
68+
for retention_days in to_tag_retention.keys():
69+
delete_date = datetime.date.today() + datetime.timedelta(days=retention_days)
70+
delete_fmt = delete_date.strftime('%Y-%m-%d')
71+
print "Will delete %d snapshots on %s" % (len(to_tag_retention[retention_days]), delete_fmt)
5972
ec.create_tags(
60-
Resources=to_tag_mount_point[vol_id],
73+
Resources=to_tag_retention[retention_days],
6174
Tags=[
62-
{'Key': 'Name', 'Value': dev_attachment},
75+
{'Key': 'DeleteOn', 'Value': delete_fmt},
6376
]
6477
)
65-
66-
for retention_days in to_tag_retention.keys():
67-
delete_date = datetime.date.today() + datetime.timedelta(days=retention_days)
68-
delete_fmt = delete_date.strftime('%Y-%m-%d')
69-
print "Will delete %d snapshots on %s" % (len(to_tag_retention[retention_days]), delete_fmt)
70-
ec.create_tags(
71-
Resources=to_tag_retention[retention_days],
72-
Tags=[
73-
{'Key': 'DeleteOn', 'Value': delete_fmt},
74-
]
75-
)

0 commit comments

Comments
 (0)