forked from paulbayer/Inventory_Scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathall_my_cfnstacks.py
More file actions
executable file
·223 lines (210 loc) · 9.19 KB
/
all_my_cfnstacks.py
File metadata and controls
executable file
·223 lines (210 loc) · 9.19 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
#!/usr/bin/env python3
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import os, sys, pprint, boto3
import Inventory_Modules, pprint
import argparse
from colorama import init,Fore,Back,Style
from botocore.exceptions import ClientError, NoCredentialsError
import logging
init()
# UsageMsg="You can provide a level to determine whether this script considers only the 'credentials' file, the 'config' file, or both."
parser = argparse.ArgumentParser(
description="We\'re going to find all resources within any of the profiles we have access to.",
prefix_chars='-+/')
parser.add_argument(
"-p","--profile",
dest="pProfile",
metavar="profile to use",
default="default",
help="To specify a specific profile, use this parameter. Default will be your default profile.")
parser.add_argument(
"-f","--fragment",
dest="pstackfrag",
metavar="CloudFormation stack fragment",
default="all",
help="String fragment of the cloudformation stack or stackset(s) you want to check for.")
parser.add_argument(
"-k","--skip",
dest="pSkipAccounts",
nargs="*",
metavar="Accounts to leave alone",
default=[],
help="These are the account numbers you don't want to screw with. Likely the core accounts.")
parser.add_argument(
"-s","--status",
dest="pstatus",
metavar="CloudFormation status",
default="active",
help="String that determines whether we only see 'CREATE_COMPLETE' or 'DELETE_COMPLETE' too")
parser.add_argument(
"-r","--region",
nargs="*",
dest="pregion",
metavar="region name string",
default=["us-east-1"],
help="String fragment of the region(s) you want to check for resources.")
parser.add_argument(
"+delete","+forreal",
dest="DeletionRun",
const=True,
default=False,
action="store_const",
help="This will delete the stacks found - without any opportunity to confirm. Be careful!!")
parser.add_argument(
'-d', '--debug',
help="Print LOTS of debugging statements",
action="store_const",
dest="loglevel",
const=logging.DEBUG, # args.loglevel = 10
default=logging.CRITICAL) # args.loglevel = 50
parser.add_argument(
'-vvv',
help="Print INFO level",
action="store_const",
dest="loglevel",
const=logging.INFO, # args.loglevel = 20
default=logging.CRITICAL) # args.loglevel = 50
parser.add_argument(
'-vv', '--verbose',
help="Be MORE verbose",
action="store_const",
dest="loglevel",
const=logging.WARNING, # args.loglevel = 30
default=logging.CRITICAL) # args.loglevel = 50
parser.add_argument(
'-v',
help="Be verbose",
action="store_const",
dest="loglevel",
const=logging.ERROR, # args.loglevel = 40
default=logging.CRITICAL) # args.loglevel = 50
args = parser.parse_args()
pProfile=args.pProfile
pRegionList=args.pregion
pstackfrag=args.pstackfrag
pstatus=args.pstatus
AccountsToSkip=args.pSkipAccounts
verbose=args.loglevel
DeletionRun=args.DeletionRun
logging.basicConfig(level=args.loglevel, format="[%(filename)s:%(lineno)s:%(levelname)s - %(funcName)30s() ] %(message)s")
##########################
ERASE_LINE = '\x1b[2K'
print(args.loglevel)
print()
if args.loglevel < 21: # INFO level
fmt='%-20s %-15s %-15s %-50s %-50s'
print(fmt % ("Account","Region","Stack Status","Stack Name","Stack ID"))
print(fmt % ("-------","------","------------","----------","--------"))
else:
fmt='%-20s %-15s %-15s %-50s'
print(fmt % ("Account","Region","Stack Status","Stack Name"))
print(fmt % ("-------","------","------------","----------"))
# RegionList=Inventory_Modules.get_ec2_regions(pRegionList)
RegionList=Inventory_Modules.get_service_regions('cloudformation',pRegionList)
ChildAccounts=Inventory_Modules.find_child_accounts2(pProfile)
ChildAccounts=Inventory_Modules.RemoveCoreAccounts(ChildAccounts,AccountsToSkip)
# pprint.pprint(AccountsToSkip)
# pprint.pprint(ChildAccounts)
# sys.exit(1)
StacksFound=[]
aws_session = boto3.Session(profile_name=pProfile)
sts_client = aws_session.client('sts')
for account in ChildAccounts:
role_arn = "arn:aws:iam::{}:role/AWSCloudFormationStackSetExecutionRole".format(account['AccountId'])
logging.info("Role ARN: %s" % role_arn)
try:
account_credentials = sts_client.assume_role(
RoleArn=role_arn,
RoleSessionName="Find-Stacks")['Credentials']
account_credentials['AccountNumber']=account['AccountId']
except ClientError as my_Error:
if str(my_Error).find("AuthFailure") > 0:
print(pProfile+": Authorization Failure for account {}".format(account['AccountId']))
elif str(my_Error).find("AccessDenied") > 0:
print(pProfile+": Access Denied Failure for account {}".format(account['AccountId']))
else:
print(pProfile+": Other kind of failure for account {}".format(account['AccountId']))
print (my_Error)
continue
for region in RegionList:
Stacks=False
try:
Stacks=Inventory_Modules.find_stacks_in_acct(account_credentials,region,pstackfrag,pstatus)
# pprint.pprint(Stacks)
logging.warning("Account: %s | Region: %s | Found %s Stacks", account['AccountId'], region, len(Stacks) )
print(ERASE_LINE,Fore.RED+"Account: {} Region: {} Found {} Stacks".format(account['AccountId'],region,len(Stacks))+Fore.RESET,end='\r')
except ClientError as my_Error:
if str(my_Error).find("AuthFailure") > 0:
print(account['AccountId']+": Authorization Failure")
if Stacks and len(Stacks) > 0:
for y in range(len(Stacks)):
StackName=Stacks[y]['StackName']
StackStatus=Stacks[y]['StackStatus']
StackID=Stacks[y]['StackId']
if args.loglevel < 21: # INFO level
print(fmt % (account['AccountId'],region,StackStatus,StackName,StackID))
else:
print(fmt % (account['AccountId'],region,StackStatus,StackName))
StacksFound.append({
'Account':account['AccountId'],
'Region':region,
'StackName':StackName,
'StackStatus':StackStatus,
'StackArn':StackID})
lAccounts=[]
lRegions=[]
lAccountsAndRegions=[]
for i in range(len(StacksFound)):
lAccounts.append(StacksFound[i]['Account'])
lRegions.append(StacksFound[i]['Region'])
lAccountsAndRegions.append((StacksFound[i]['Account'],StacksFound[i]['Region']))
print(ERASE_LINE)
print(Fore.RED+"Looked through",len(StacksFound),"Stacks across",len(ChildAccounts),"accounts across",len(RegionList),"regions"+Fore.RESET)
print()
if args.loglevel < 21: # INFO level
print("The list of accounts and regions:")
pprint.pprint(list(sorted(set(lAccountsAndRegions))))
# pprint.pprint(StacksFound)
if DeletionRun and ('GuardDuty' in pstackfrag):
logging.warning("Deleting %s stacks",len(StacksFound))
for y in range(len(StacksFound)):
role_arn = "arn:aws:iam::{}:role/AWSCloudFormationStackSetExecutionRole".format(StacksFound[y]['Account'])
cfn_client=aws_session.client('cloudformation')
account_credentials = sts_client.assume_role(
RoleArn=role_arn,
RoleSessionName="Delete-Stacks")['Credentials']
account_credentials['AccountNumber']=StacksFound[y]['Account']
print("Deleting stack {} from Account {} in region {} with status: {}".format(StacksFound[y]['StackName'],StacksFound[y]['Account'],StacksFound[y]['Region'],StacksFound[y]['StackStatus']))
""" This next line is BAD because it's hard-coded for GuardDuty, but we'll fix that eventually """
if StacksFound[y]['StackStatus'] == 'DELETE_FAILED':
# This deletion generally fails because the Master Detector doesn't properly delete (and it's usually already deleted due to some other script) - so we just need to delete the stack anyway - and ignore the actual resource.
response=Inventory_Modules.delete_stack2(account_credentials,StacksFound[y]['Region'],StacksFound[y]['StackName'],RetainResources=True,ResourcesToRetain=["MasterDetector"])
else:
response=Inventory_Modules.delete_stack2(account_credentials,StacksFound[y]['Region'],StacksFound[y]['StackName'])
elif DeletionRun:
logging.warning("Deleting %s stacks",len(StacksFound))
for y in range(len(StacksFound)):
role_arn = "arn:aws:iam::{}:role/AWSCloudFormationStackSetExecutionRole".format(StacksFound[y]['Account'])
cfn_client=aws_session.client('cloudformation')
account_credentials = sts_client.assume_role(
RoleArn=role_arn,
RoleSessionName="Delete-Stacks")['Credentials']
account_credentials['AccountNumber']=StacksFound[y]['Account']
print("Deleting stack {} from account {} in region {} with status: {}".format(StacksFound[y]['StackName'],StacksFound[y]['Account'],StacksFound[y]['Region'],StacksFound[y]['StackStatus']))
response=Inventory_Modules.delete_stack2(account_credentials,StacksFound[y]['Region'],StacksFound[y]['StackName'])
pprint.pprint(response)
print()
print("Thanks for using this script...")