-
Notifications
You must be signed in to change notification settings - Fork 73
/
aws-count-tag-names.py
executable file
·185 lines (154 loc) · 5.61 KB
/
aws-count-tag-names.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
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
#!/usr/bin/env python
"""
Using boto3, scan all AWS resources in the current account, and produce a report
detailing all of the distinct tag names and the number of resources having each
one.
If you have ideas for improvements, or want the latest version, it's at:
<https://github.com/jantman/misc-scripts/blob/master/aws-count-tag-names.py>
Copyright 2016 Jason Antman <[email protected]> <http://www.jasonantman.com>
Free for any use provided that patches are submitted back to me.
REQUIREMENTS:
* boto3
* texttable
pip install boto3 texttable
CHANGELOG:
2017-06-27 Jason Antman <[email protected]>:
- initial version of script
"""
import sys
import argparse
import logging
from boto3 import resource, client
from collections import defaultdict
from texttable import Texttable
FORMAT = "[%(asctime)s %(levelname)s] %(message)s"
logging.basicConfig(level=logging.WARNING, format=FORMAT)
logger = logging.getLogger()
# suppress boto3 internal logging below WARNING level
boto3_log = logging.getLogger("boto3")
boto3_log.setLevel(logging.WARNING)
boto3_log.propagate = True
# suppress botocore internal logging below WARNING level
botocore_log = logging.getLogger("botocore")
botocore_log.setLevel(logging.WARNING)
botocore_log.propagate = True
class TagCounter(object):
def __init__(self):
self.tags = defaultdict(int)
self.res_count = 0
def print_table(self):
print("Count of resource tags for %d EC2 Instances, Images, Security "
"Groups, Snapshots, Volumes, and ASGs\n" % self.res_count)
t = Texttable()
t.set_cols_dtype(['t', 'i'])
rows = [['Tag Name', 'Count']]
for k in sorted(self.tags.keys(), key=lambda s: s.lower()):
rows.append([k, self.tags[k]])
t.add_rows(rows)
print(t.draw() + "\n")
print(
"Generated by: https://github.com/jantman/misc-scripts/blob/"
"master/aws-count-tag-names.py\n")
def run(self):
logger.debug('Getting regions...')
regions = self.get_region_names()
logger.debug('Regions: %s', regions)
for r in regions:
self.tags_for_region(r)
def get_region_names(self):
conn = client('ec2')
res = conn.describe_regions()
regions = []
for r in res['Regions']:
regions.append(r['RegionName'])
return regions
def tags_for_region(self, region_name):
logger.info('Getting tags for region: %s', region_name)
logger.debug('Querying EC2 Instances...')
res = resource('ec2', region_name=region_name)
for i in res.instances.all():
self.res_count += 1
if i.tags is None:
continue
for t in i.tags:
self.tags[t['Key']] += 1
logger.debug('Querying EC2 Images (AMIs)...')
for i in res.images.all():
self.res_count += 1
if i.tags is None:
continue
for t in i.tags:
self.tags[t['Key']] += 1
logger.debug('Querying EC2 Security Groups...')
for i in res.security_groups.all():
self.res_count += 1
if i.tags is None:
continue
for t in i.tags:
self.tags[t['Key']] += 1
logger.debug('Querying EC2 Snapshots...')
for i in res.snapshots.all():
self.res_count += 1
if i.tags is None:
continue
for t in i.tags:
self.tags[t['Key']] += 1
logger.debug('Querying EC2 Volumes...')
for i in res.volumes.all():
self.res_count += 1
if i.tags is None:
continue
for t in i.tags:
self.tags[t['Key']] += 1
logger.debug('Querying ASGs...')
cli = client('autoscaling', region_name=region_name)
p = cli.get_paginator('describe_auto_scaling_groups')
for resp in p.paginate():
for asg in resp['AutoScalingGroups']:
self.res_count += 1
for t in asg['Tags']:
self.tags[t['Key']] += 1
logger.info('Done with region.')
def parse_args(argv):
"""
parse arguments/options
this uses the new argparse module instead of optparse
see: <https://docs.python.org/2/library/argparse.html>
"""
p = argparse.ArgumentParser(description='Count distinct AWS tags')
p.add_argument('-v', '--verbose', dest='verbose', action='count', default=0,
help='verbose output. specify twice for debug-level output.')
args = p.parse_args(argv)
return args
def set_log_info():
"""set logger level to INFO"""
set_log_level_format(logging.INFO,
'%(asctime)s %(levelname)s:%(name)s:%(message)s')
def set_log_debug():
"""set logger level to DEBUG, and debug-level output format"""
set_log_level_format(
logging.DEBUG,
"%(asctime)s [%(levelname)s %(filename)s:%(lineno)s - "
"%(name)s.%(funcName)s() ] %(message)s"
)
def set_log_level_format(level, format):
"""
Set logger level and format.
:param level: logging level; see the :py:mod:`logging` constants.
:type level: int
:param format: logging formatter format string
:type format: str
"""
formatter = logging.Formatter(fmt=format)
logger.handlers[0].setFormatter(formatter)
logger.setLevel(level)
if __name__ == "__main__":
args = parse_args(sys.argv[1:])
# set logging level
if args.verbose > 1:
set_log_debug()
elif args.verbose == 1:
set_log_info()
script = TagCounter()
script.run()
script.print_table()