-
Notifications
You must be signed in to change notification settings - Fork 0
/
orphaned_resources.py
executable file
·76 lines (57 loc) · 2.08 KB
/
orphaned_resources.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/env python
from boto3.session import Session
import botocore
def get_stack_outputvars(stack, ec2):
return {v['OutputKey']: v['OutputValue'] for v in stack.outputs}
def get_args():
import argparse
argp = argparse.ArgumentParser()
argp.add_argument('--profile')
argp.add_argument('--yes', default=False, action='store_true')
argp.add_argument('--region', default='us-east-1')
return argp
def get_orphaned_resources(cff, ec2, s3, args):
# s3 buckets
stack_buckets = {
bk.name: bk for bk in s3.buckets.all()
if '-pcfelasticruntimes' in bk.name or
'-pcfopsmanager' in bk.name}
stt = list(cff.stacks.all())
# bucket
for ac in [st for st in stt if st.stack_status == 'CREATE_COMPLETE']:
if ac.outputs is None:
continue
svars = get_stack_outputvars(ac, ec2)
for sk, sv in svars.items():
if sv in stack_buckets:
del stack_buckets[sv]
print len(stack_buckets), " Buckets are not owned by active stacks"
if confirm_oprn("S3 Buckets", len(stack_buckets), args.yes) is False:
return -1
for bk in stack_buckets:
print "Emptying {}".format(bk.name)
try:
bk.objects.delete()
except botocore.exceptions.ClientError as ce:
if ce.response['Error']['Code'] != '404':
print ce
def confirm_oprn(resource_type, resource_number, yes):
print "Removing {} {}".format(resource_number, resource_type)
if resource_number == 0:
return False
if yes is True:
return True
confirm = raw_input("This cannot be recovered. Proceed? YES/NO ")
if confirm.lower() != 'yes':
print "Skipping"
return False
def main(argv):
args = get_args().parse_args(argv)
session = Session(profile_name=args.profile, region_name=args.region)
ec2 = session.resource("ec2")
s3 = session.resource("s3")
cff = session.resource("cloudformation")
get_orphaned_resources(cff, ec2, s3, args)
if __name__ == "__main__":
import sys
sys.exit(main(sys.argv[1:]))