forked from paulbayer/Inventory_Scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathall_my_topics.py
More file actions
executable file
·152 lines (137 loc) · 5.54 KB
/
all_my_topics.py
File metadata and controls
executable file
·152 lines (137 loc) · 5.54 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
#!/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 sns topics 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(
"-r","--region",
dest="pRegion",
metavar="region name string",
nargs='*',
default=["us-east-1"],
help="String fragment of the region(s) you want to check for resources.")
parser.add_argument(
"-t","--topic",
dest="pTopicFrag",
default=["all"],
nargs='*',
metavar="topic name string",
help="String fragment of the Topic you want to find.")
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
pTopicFrag=args.pTopicFrag
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"]
NumTopicsFound = 0
NumRegions = 0
print()
fmt='%-20s %-15s %-25s'
print(fmt % ("Account","Region","SNS Topic"))
print(fmt % ("-------","------","---------"))
RegionList=Inventory_Modules.get_ec2_regions(pRegionList,pProfile)
ChildAccounts=Inventory_Modules.find_child_accounts2(pProfile)
AdminRole="AWSCloudFormationStackSetExecutionRole"
logging.info("# of Regions: %s" % len(RegionList))
logging.info("# of Child Accounts: %s" % len(ChildAccounts))
for i in range(len(ChildAccounts)):
aws_session = boto3.Session(profile_name=ChildAccounts[i]['ParentProfile'])
sts_client = aws_session.client('sts')
logging.info("Connecting to account %s using Parent Profile %s:",ChildAccounts[i]['AccountId'],ChildAccounts[i]['ParentProfile'])
role_arn = "arn:aws:iam::{}:role/{}".format(ChildAccounts[i]['AccountId'],AdminRole)
try:
account_credentials = sts_client.assume_role(
RoleArn=role_arn,
RoleSessionName="Find-Instances")['Credentials']
account_credentials['AccountNumber']=ChildAccounts[i]['AccountId']
except ClientError as my_Error:
if str(my_Error).find("AuthFailure") > 0:
print("{}: Authorization Failure for account {}".format(ChildAccounts[i]['ParentProfile'], ChildAccounts[i]['AccountId']))
elif str(my_Error).find("AccessDenied") > 0:
print("{}: Access Denied Failure for account {}".format(ChildAccounts[i]['ParentProfile'], ChildAccounts[i]['AccountId']))
print(my_Error)
else:
print("{}: Other kind of failure for account {}".format(ChildAccounts[i]['ParentProfile'], ChildAccounts[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:
logging.info("Looking for Topics")
Topics=Inventory_Modules.find_sns_topics(account_credentials,region,pTopicFrag)
TopicNum=len(Topics)
print(ERASE_LINE,"Looking in account "+Fore.RED+"{}".format(ChildAccounts[i]['AccountId']),Fore.RESET+"in {} where we found {} Topics".format(region,TopicNum),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,ChildAccounts[i]['AccountId'],region))
except TypeError as my_Error:
print("Error:",my_Error)
pass
for y in range(len(Topics)):
print(fmt % (ChildAccounts[i]['AccountId'],region,Topics[y]))
NumTopicsFound += 1
else:
continue
print()
print("Found {} Topics across {} accounts across {} regions".format(NumTopicsFound,len(ChildAccounts),len(RegionList)))
print()
print("Thank you for using this script.")