forked from paulbayer/Inventory_Scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathall_my_orgs.py
More file actions
executable file
·293 lines (272 loc) · 10.7 KB
/
all_my_orgs.py
File metadata and controls
executable file
·293 lines (272 loc) · 10.7 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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
#!/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
import sys
import logging
import argparse
import Inventory_Modules
from botocore.exceptions import ClientError, NoCredentialsError, InvalidConfigError
from colorama import init,Fore,Style
init()
parser = argparse.ArgumentParser(
description="We\'re going to find all accounts within any of the organizations we have access to.",
prefix_chars='-+/')
ProfileGroup = parser.add_mutually_exclusive_group()
ProfileGroup.add_argument(
"-p","--profile",
dest="pProfile",
metavar="Profile",
default="all", # Default to everything
help="Which single profile do you want to run for?")
ProfileGroup.add_argument(
"-l","--listprofiles",
dest="pProfiles",
metavar="Profiles",
nargs="*",
default=[], # Default to nothing
help="Which list of profiles do you want to run for?")
parser.add_argument(
'-R', '--root',
help="Display only the root accounts found in the profiles",
action="store_const",
dest="rootonly",
const=True,
default=False)
parser.add_argument(
'-s', '--q', '--short',
help="Display only brief listing of the root accounts, and not the Child Accounts under them",
action="store_const",
dest="shortform",
const=True,
default=False)
parser.add_argument(
'-v',
help="Be verbose",
action="store_const",
dest="loglevel",
const=logging.ERROR, # args.loglevel = 40
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(
'-vvv',
help="Print debugging statements",
action="store_const",
dest="loglevel",
const=logging.INFO, # args.loglevel = 20
default=logging.CRITICAL) # args.loglevel = 50
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
args=parser.parse_args()
pProfile=args.pProfile
pProfiles=args.pProfiles
verbose=args.loglevel
rootonly=args.rootonly
shortform=args.shortform
logging.basicConfig(level=args.loglevel, format="[%(filename)s:%(lineno)s:%(levelname)s - %(funcName)20s() ] %(message)s")
SkipProfiles=["default"]
ERASE_LINE = '\x1b[2K'
RootAccts=[] # List of the Organization Root's Account Number
RootProfiles=[] # List of the Organization Root's profiles
"""
Because there's two ways for the user to provide profiles, we have to consider four scenarios:
1. They provided no input
* We'll use the pProfile default of "all"
2. They provided input using the pProfile parameter of a specific profile
* That's the case we already handle
3. They provided a list of profiles using the pProfiles parameter
* This is the new case, that we'll cycle through
4. They provided both the pProfile AND pProfiles parameters.
* argparse will stop the user from doing that!
"""
logging.info("Profile: %s",pProfile)
logging.info("Profiles: %s",str(pProfiles))
if pProfile == "all" and pProfiles == []: # Use case #1 from above
logging.info("Use Case #1")
logging.warning("Profile is set to all")
ShowEverything=True
elif not pProfile == "all": # Use case #2 from above
logging.info("Use Case #2")
logging.warning("Profile is set to %s",pProfile)
AcctNum = Inventory_Modules.find_account_number(pProfile)
AcctAttr = Inventory_Modules.find_org_attr(pProfile)
MasterAcct = AcctAttr['MasterAccountId']
OrgId = AcctAttr['Id']
if AcctNum==MasterAcct:
logging.warning("This is a root account - showing info only for %s",pProfile)
RootAcct=True
ShowEverything=False
else:
print()
print(Fore.RED + "If you're going to provide a profile, it's supposed to be a Master Billing Account profile!!" + Fore.RESET)
print("Continuing to run the script - but for all profiles.")
ShowEverything=True
else: # Use case #3 from above
logging.info("Use Case #3")
logging.warning("Multiple profiles have been provided: %s. Going through one at a time...",str(pProfiles))
for profile in pProfiles:
AcctNum = Inventory_Modules.find_account_number(profile)
AcctAttr = Inventory_Modules.find_org_attr(profile)
MasterAcct = AcctAttr['MasterAccountId']
OrgId = AcctAttr['Id']
if AcctNum==MasterAcct:
filename=sys.argv[0]
logging.info("Running the script again with %s as your profile",profile)
ShowEverything=False
os.system("python3 "+filename+" -p "+profile)
else:
print()
print(Fore.RED + "Provided profile: {} isn't a Master Billing Account profile!!".format(profile) + Fore.RESET)
print("Skipping...")
ShowEverything=False
continue
sys.exit("Finished %s profiles!" % len(pProfiles)) # Finished the multiple profiles provided.
"""
TODO:
- If they provide a profile that isn't a root profile, you should find out which org it belongs to, and then show the org for that. This will be difficult, since we don't know which profile that belongs to. Hmmm...
"""
if ShowEverything:
fmt='%-23s %-15s %-27s %-12s %-10s'
print ("------------------------------------")
print (fmt % ("Profile Name","Account Number","Master Org Acct","Org ID","Root Acct?"))
print (fmt % ("------------","--------------","---------------","------","----------"))
for profile in Inventory_Modules.get_profiles2(SkipProfiles,"all"):
AcctNum = "Blank Acct"
MasterAcct = "Blank Root"
OrgId = "o-xxxxxxxxxx"
Email = "Email not available"
RootId = "r-xxxx"
ErrorFlag = False
try:
AcctNum = Inventory_Modules.find_account_number(profile)
logging.info("AccountNumber: {}".format(AcctNum))
if AcctNum == '123456789012':
ErrorFlag = True
pass
else:
AcctAttr = Inventory_Modules.find_org_attr(profile)
MasterAcct = AcctAttr['MasterAccountId']
OrgId = AcctAttr['Id']
except ClientError as my_Error:
ErrorFlag = True
if str(my_Error).find("AWSOrganizationsNotInUseException") > 0:
MasterAcct="Not an Org Account"
elif str(my_Error).find("AccessDenied") > 0:
MasterAcct="Acct not auth for Org API."
elif str(my_Error).find("InvalidClientTokenId") > 0:
MasterAcct="Credentials Invalid."
elif str(my_Error).find("ExpiredToken") > 0:
MasterAcct="Token Expired."
else:
print("Client Error")
print(my_Error)
except InvalidConfigError as my_Error:
ErrorFlag = True
if str(my_Error).find("does not exist") > 0:
ErrorMessage=str(my_Error)[str(my_Error).find(":"):]
print(ErrorMessage)
else:
print("Credentials Error")
print(my_Error)
except NoCredentialsError as my_Error:
ErrorFlag = True
if str(my_Error).find("Unable to locate credentials") > 0:
MasterAcct="This profile doesn't have credentials."
else:
print("Credentials Error")
print(my_Error)
if AcctNum==MasterAcct and not ErrorFlag:
RootAcct=True
RootAccts.append(MasterAcct)
RootProfiles.append(profile)
Email = AcctAttr['MasterAccountEmail']
logging.info('Email: %s',Email)
else:
RootAcct=False
'''
If I create a dictionary from the Root Accts and Root Profiles Lists -
I can use that to determine which profile belongs to the root user of my (child) account.
But this dictionary is only guaranteed to be valid after ALL profiles have been checked,
so... it doesn't solve our issue - unless we don't write anything to the screen until *everything* is done,
and we keep all output in another dictionary - where we can populate the missing data at the end...
but that takes a long time, since nothing would be sent to the screen in the meantime.
'''
# dictionary.update(dict(zip(RootAccts, RootProfiles)))
# Print results for this profile
if RootAcct:
print(Fore.RED + fmt % (profile,AcctNum,MasterAcct,OrgId,RootAcct)+Style.RESET_ALL)
elif rootonly: # If I'm looking for only the root accounts, when I find something that isn't a root account, don't print anything and continue on.
print(ERASE_LINE,"{} isn't a root account".format(profile),end="\r")
else:
print (fmt % (profile,AcctNum,MasterAcct,OrgId,RootAcct))
print()
print("-------------------")
if not shortform:
fmt='%-23s %-15s %-6s'
child_fmt="\t\t%-20s %-20s"
print()
print(fmt % ("Organization's Profile","Root Account","ALZ"))
print(fmt % ("----------------------","------------","---"))
NumOfAccounts=0
for profile in RootProfiles:
child_accounts={}
MasterAcct=Inventory_Modules.find_account_number(profile)
child_accounts=Inventory_Modules.find_child_accounts(profile)
landing_zone=Inventory_Modules.find_if_alz(profile)['ALZ']
NumOfAccounts=NumOfAccounts + len(child_accounts)
if landing_zone:
fmt='%-23s '+Style.BRIGHT+'%-15s '+Style.RESET_ALL+Fore.RED+'%-6s '+Fore.RESET
else:
fmt='%-23s '+Style.BRIGHT+'%-15s '+Style.RESET_ALL+'%-6s'
print(fmt % (profile,MasterAcct,landing_zone))
print(child_fmt % ("Child Account Number","Child Email Address"))
for account in sorted(child_accounts):
print(child_fmt % (account,child_accounts[account]))
print()
print("Number of Organizations:",len(RootProfiles))
print("Number of Organization Accounts:",NumOfAccounts)
elif not ShowEverything:
fmt='%-23s %-15s %-6s'
child_fmt="\t\t%-20s %-20s"
print()
print(fmt % ("Organization's Profile","Root Account","ALZ"))
print(fmt % ("----------------------","------------","---"))
NumOfAccounts=0
child_accounts={}
MasterAcct=Inventory_Modules.find_account_number(pProfile)
child_accounts=Inventory_Modules.find_child_accounts(pProfile)
landing_zone=Inventory_Modules.find_if_alz(pProfile)['ALZ']
NumOfAccounts=NumOfAccounts + len(child_accounts)
if landing_zone:
fmt='%-23s '+Style.BRIGHT+'%-15s '+Style.RESET_ALL+Fore.RED+'%-6s '+Fore.RESET
else:
fmt='%-23s '+Style.BRIGHT+'%-15s '+Style.RESET_ALL+'%-6s'
print(fmt % (pProfile,MasterAcct,landing_zone))
print(child_fmt % ("Child Account Number","Child Email Address"))
for account in sorted(child_accounts):
print(child_fmt % (account,child_accounts[account]))
print()
print("Number of Organization Accounts:",NumOfAccounts)