forked from paulbayer/Inventory_Scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathall_my_vpcs2.py
More file actions
executable file
·205 lines (188 loc) · 8.47 KB
/
all_my_vpcs2.py
File metadata and controls
executable file
·205 lines (188 loc) · 8.47 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
#!/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, datetime
import Inventory_Modules
import argparse, boto3
from colorama import init,Fore,Back,Style
from botocore.exceptions import ClientError, NoCredentialsError
import logging
init()
parser = argparse.ArgumentParser(
description="This script finds vpcs (or only default vpcs) in all accounts within our Organization.",
prefix_chars='-+/')
parser.add_argument(
"-p","--profile",
dest="pProfile",
metavar="profile to use",
default="default",
help="Preferred to specify a root profile. Default will be all Master profiles")
parser.add_argument(
"--default",
dest="pDefault",
metavar="Looking for default VPCs only",
action="store_const",
default=False,
const=True,
help="Flag to determine whether we're looking for default VPCs only.")
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(
'-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 statements",
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
pDefault=args.pDefault
verbose=args.loglevel
logging.basicConfig(level=args.loglevel, format="[%(filename)s:%(lineno)s:%(levelname)s - %(funcName)30s() ] %(message)s")
##########################
ERASE_LINE = '\x1b[2K'
SkipProfiles=["default"]
NumVpcsFound = 0
NumRegions = 0
print()
fmt='%-20s %-15s %-21s %-20s %-12s %-10s'
print(fmt % ("Account","Region","Vpc ID","CIDR","Is Default?","Vpc Name"))
print(fmt % ("-------","------","------","----","-----------","--------"))
RegionList=Inventory_Modules.get_ec2_regions(pRegionList,pProfile)
SoughtAllProfiles=False
AllChildAccounts=[]
AdminRole="AWSCloudFormationStackSetExecutionRole"
if pDefault:
vpctype="default"
else:
# I use the backspace character to make the sentence format work, since it backspaces over the prior space.
# Totally cosmetic, but I'm an idiot that spends an hour to figure out how best to do this.
vpctype="\b"
if pProfile in ['all','ALL','All']:
# print(Fore.RED+"Doesn't yet work to specify 'all' profiles, since it takes a long time to go through and find only those profiles that either Org Masters, or stand-alone accounts",Fore.RESET)
# sys.exit(1)
SoughtAllProfiles=True
print("Since you specified 'all' profiles, we going to look through ALL of your profiles. Then we go through and determine which profiles represent the Master of an Organization and which are stand-alone accounts. This will enable us to go through all accounts you have access to for inventorying.")
logging.error("Time: %s",datetime.datetime.now())
ProfileList=Inventory_Modules.get_parent_profiles('all',SkipProfiles)
logging.error("Time: %s",datetime.datetime.now())
logging.error("Found %s root profiles",len(ProfileList))
# logging.info("Profiles Returned from function get_parent_profiles: %s",pProfile)
else:
ProfileList=[pProfile]
for profile in ProfileList:
print(ERASE_LINE,"Gathering all account data from {} profile".format(profile),end="\r")
# if not SoughtAllProfiles:
logging.info("Checking to see which profiles are root profiles")
ProfileIsRoot=Inventory_Modules.find_if_org_root(profile)
logging.info("---%s---",ProfileIsRoot)
if ProfileIsRoot == 'Root':
logging.info("Parent Profile name: %s",profile)
ChildAccounts=Inventory_Modules.find_child_accounts2(profile)
# ChildAccounts=Inventory_Modules.RemoveCoreAccounts(ChildAccounts,AccountsToSkip)
AllChildAccounts=AllChildAccounts+ChildAccounts
elif ProfileIsRoot == 'StandAlone':
logging.info("Parent Profile name: %s",profile)
MyAcctNumber=Inventory_Modules.find_account_number(profile)
Accounts=[{'ParentProfile':profile,'AccountId':MyAcctNumber,'AccountEmail':'noonecares@doesntmatter.com'}]
AllChildAccounts=AllChildAccounts+Accounts
elif ProfileIsRoot == 'Child':
logging.info("Profile name: %s is a child profile",profile)
MyAcctNumber=Inventory_Modules.find_account_number(profile)
Accounts=[{'ParentProfile':profile,'AccountId':MyAcctNumber,'AccountEmail':'noonecares@doesntmatter.com'}]
AllChildAccounts=Accounts
logging.info("# of Regions: %s" % len(RegionList))
logging.info("# of Master Accounts: %s" % len(ProfileList))
logging.info("# of Child Accounts: %s" % len(AllChildAccounts))
for i in range(len(AllChildAccounts)):
aws_session = boto3.Session(profile_name=AllChildAccounts[i]['ParentProfile'])
sts_client = aws_session.client('sts')
logging.info("Connecting to account %s using Parent Profile %s:",AllChildAccounts[i]['AccountId'],AllChildAccounts[i]['ParentProfile'])
role_arn = "arn:aws:iam::{}:role/{}".format(AllChildAccounts[i]['AccountId'],AdminRole)
try:
account_credentials = sts_client.assume_role(
RoleArn=role_arn,
RoleSessionName="Find-Instances")['Credentials']
account_credentials['AccountNumber']=AllChildAccounts[i]['AccountId']
except ClientError as my_Error:
if str(my_Error).find("AuthFailure") > 0:
print("{}: Authorization Failure for account {}".format(AllChildAccounts[i]['ParentProfile'], AllChildAccounts[i]['AccountId']))
elif str(my_Error).find("AccessDenied") > 0:
print("{}: Access Denied Failure for account {}".format(AllChildAccounts[i]['ParentProfile'], AllChildAccounts[i]['AccountId']))
print(my_Error)
else:
print("{}: Other kind of failure for account {}".format(AllChildAccounts[i]['ParentProfile'], AllChildAccounts[i]['AccountId']))
print (my_Error)
break
# NumRegions += 1
# NumProfilesInvestigated = 0 # I only care about the last run - so I don't get profiles * regions.
for region in RegionList:
# NumProfilesInvestigated += 1
try:
Vpcs=Inventory_Modules.find_account_vpcs(account_credentials,region,pDefault)
VpcNum=len(Vpcs['Vpcs']) if Vpcs['Vpcs']==[] else 0
print(ERASE_LINE,"Looking in account "+Fore.RED+"{}".format(AllChildAccounts[i]['AccountId']),Fore.RESET+"in {} where we found {} {} Vpcs".format(region,VpcNum,vpctype),end='\r')
except ClientError as my_Error:
if str(my_Error).find("AuthFailure") > 0:
print(ERASE_LINE, "{} :Authorization Failure for account: {} in region {}".format(profile,AllChildAccounts[i]['AccountId'],region))
except TypeError as my_Error:
print(my_Error)
pass
if 'Vpcs' in Vpcs and len(Vpcs['Vpcs']) > 0:
for y in range(len(Vpcs['Vpcs'])):
VpcId=Vpcs['Vpcs'][y]['VpcId']
IsDefault=Vpcs['Vpcs'][y]['IsDefault']
CIDR=Vpcs['Vpcs'][y]['CidrBlock']
if 'Tags' in Vpcs['Vpcs'][y]:
for z in range(len(Vpcs['Vpcs'][y]['Tags'])):
if Vpcs['Vpcs'][y]['Tags'][z]['Key']=="Name":
VpcName=Vpcs['Vpcs'][y]['Tags'][z]['Value']
else:
VpcName="No name defined"
print(fmt % (Vpcs['Vpcs'][y]['OwnerId'],region,VpcId,CIDR,IsDefault,VpcName))
NumVpcsFound += 1
else:
continue
print(ERASE_LINE)
print("Found {} {} Vpcs across {} accounts across {} regions".format(NumVpcsFound,vpctype,len(AllChildAccounts),len(RegionList)))
print()
print("Thank you for using this script.")