-
Notifications
You must be signed in to change notification settings - Fork 0
/
unused_aws_resources.py
507 lines (397 loc) · 21.2 KB
/
unused_aws_resources.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
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
"""
SYNOPSIS
--------
Get the details of unused resources present across regions in the AWS account
DESCRIPTION
-----------
This script provides a detailed overview of the number of unused resources present in the AWS account.
It provides service-wise details of unused resources lying around in all the regions of the AWS account.
PREREQUISITES
-------------
- Workstation with Python version 3 and above
- AWS python-based SDK: boto3
Installation command: pip3 install boto3
- pandas framework and openpyxl for reporting operations (xlsx file).
Installation command(s):
- pip3 install pandas
- pip3 install openpyxl
- User credentials (Access Key Id and Secret Accces Key) of a user having atleast the Security Audit permission and above on the AWS account
EXAMPLE
-------
This script can be executed on a python compiler (AWS Cloudshell, Powershell, bash, any command line tool with python installed)
Command: python ./unused_aws_resources.py --accessKey <AWS Access Key Id> --secretKey <AWS Secret Access Key>
OUTPUT
------
- The script will provide a summarized count of all unused resources in the account.
- For a detailed view, the user can refer to the .xlsx file that will be generated by the script.
"""
import json
import boto3
import argparse
import multiprocessing
import csv
import os
import pandas as pd
import sys
import glob
from urllib.request import urlopen
def ebs_volume(function, credentials, unused_resource_count, region_list):
print('Scanning EBS Volumes')
volume_count = 0
unused_volume_detail = []
for region in region_list:
try:
ec2 = boto3.resource('ec2', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'], region_name=region)
volumes = list(ec2.volumes.all())
unused_volumes = set([volume.volume_id for volume in volumes if volume.state == 'available'])
for volume_id in unused_volumes:
unused_volume_detail.append({'ResourceType':'AWS::EC2::Volume','ResourceId':volume_id,'Region':region})
volume_count+=len(unused_volumes)
except:
pass
if volume_count:
unused_volume_detail = json.loads(json.dumps(unused_volume_detail))
f = csv.writer(open("./aws_logs/ebs_volume.csv", "w", newline=''))
f.writerow(["ResourceType", "ResourceId", "Region"])
for unused_volume_detail in unused_volume_detail:
f.writerow([unused_volume_detail["ResourceType"],
unused_volume_detail["ResourceId"],
unused_volume_detail["Region"]])
unused_resource_count[function] = volume_count
def elastic_ip(function, credentials, unused_resource_count, region_list):
print('Scanning Elastic IPs')
eip_count = 0
unused_eip_detail = []
for region in region_list:
try:
ec2_client = boto3.client('ec2', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'], region_name=region)
eip_data = ec2_client.describe_addresses()['Addresses']
for eip in eip_data:
try:
AssociationId = eip['AssociationId']
except:
AssociationId = ''
if not AssociationId:
unused_eip_detail.append({'ResourceType':'AWS::EC2::EIP','ResourceId':eip['AllocationId'],'Region':region})
eip_count += 1
except:
pass
if eip_count:
unused_eip_detail = json.loads(json.dumps(unused_eip_detail))
f = csv.writer(open("./aws_logs/elastic_ip.csv", "w", newline=''))
f.writerow(["ResourceType", "ResourceId", "Region"])
for unused_eip_detail in unused_eip_detail:
f.writerow([unused_eip_detail["ResourceType"],
unused_eip_detail["ResourceId"],
unused_eip_detail["Region"]])
unused_resource_count[function] = eip_count
def network_interface(function, credentials, unused_resource_count, region_list):
print('Scanning Network Interfaces')
ni_count = 0
unused_ni_detail = []
for region in region_list:
try:
ec2 = boto3.resource('ec2', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'], region_name=region)
network_interfaces = list(ec2.network_interfaces.all())
unused_nis = set([ni.network_interface_id for ni in network_interfaces if ni.status == 'available'])
for network_interface_id in unused_nis:
unused_ni_detail.append({'ResourceType':'AWS::EC2::NetworkInterface','ResourceId':network_interface_id,'Region':region})
ni_count+=len(unused_nis)
except:
pass
if ni_count:
unused_ni_detail = json.loads(json.dumps(unused_ni_detail))
f = csv.writer(open("./aws_logs/network_interface.csv", "w", newline=''))
f.writerow(["ResourceType", "ResourceId", "Region"])
for unused_ni_detail in unused_ni_detail:
f.writerow([unused_ni_detail["ResourceType"],
unused_ni_detail["ResourceId"],
unused_ni_detail["Region"]])
unused_resource_count[function] = ni_count
def vpc(function, credentials, unused_resource_count, region_list):
print('Scanning VPCs')
vpc_count = 0
unused_vpc_detail = []
for region in region_list:
try:
ec2 = boto3.resource('ec2', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'], region_name=region)
vpcs = list(ec2.vpcs.all())
network_interfaces = list(ec2.network_interfaces.all())
all_vpcs = set([vpc.vpc_id for vpc in vpcs])
all_active_vpcs = set([vpc['VpcId'] for ni in network_interfaces for vpc in ni.vpc])
unused_vpcs = all_vpcs - all_active_vpcs
for vpcid in unused_vpcs:
unused_vpc_detail.append({'ResourceType':'AWS::EC2::VPC','ResourceId':vpcid,'Region':region})
vpc_count+=len(unused_vpcs)
except:
pass
if vpc_count:
unused_vpc_detail = json.loads(json.dumps(unused_vpc_detail))
f = csv.writer(open("./aws_logs/vpc.csv", "w", newline=''))
f.writerow(["ResourceType", "ResourceId", "Region"])
for unused_vpc_detail in unused_vpc_detail:
f.writerow([unused_vpc_detail["ResourceType"],
unused_vpc_detail["ResourceId"],
unused_vpc_detail["Region"]])
unused_resource_count[function] = vpc_count
def subnet(function, credentials, unused_resource_count, region_list):
print('Scanning Subnets')
subnet_count = 0
unused_subnet_detail = []
for region in region_list:
try:
ec2 = boto3.resource('ec2', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'], region_name=region)
subnets = list(ec2.subnets.all())
network_interfaces = list(ec2.network_interfaces.all())
all_subnets = set([subnet.subnet_id for subnet in subnets])
all_active_subnets = set([subnet['SubnetId'] for ni in network_interfaces for subnet in ni.subnet])
unused_subnets = all_subnets - all_active_subnets
for subnetid in unused_subnets:
unused_subnet_detail.append({'ResourceType':'AWS::EC2::Subnet','ResourceId':subnetid,'Region':region})
subnet_count+=len(unused_subnets)
except:
pass
if subnet_count:
unused_subnet_detail = json.loads(json.dumps(unused_subnet_detail))
f = csv.writer(open("./aws_logs/subnet.csv", "w", newline=''))
f.writerow(["ResourceType", "ResourceId", "Region"])
for unused_subnet_detail in unused_subnet_detail:
f.writerow([unused_subnet_detail["ResourceType"],
unused_subnet_detail["ResourceId"],
unused_subnet_detail["Region"]])
unused_resource_count[function] = subnet_count
def security_group(function, credentials, unused_resource_count, region_list):
print('Scanning Security Groups')
sg_count = 0
unused_sg_detail = []
for region in region_list:
try:
ec2 = boto3.resource('ec2', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'], region_name=region)
sgs = list(ec2.security_groups.all())
network_interfaces = list(ec2.network_interfaces.all())
all_sgs = set([sg.group_id for sg in sgs])
all_inst_sgs = set([sg['GroupId'] for ni in network_interfaces for sg in ni.groups])
unused_sgs = all_sgs - all_inst_sgs
for sgid in unused_sgs:
unused_sg_detail.append({'ResourceType':'AWS::EC2::SecurityGroup','ResourceId':sgid,'Region':region})
sg_count+=len(unused_sgs)
except:
pass
if sg_count:
unused_sg_detail = json.loads(json.dumps(unused_sg_detail))
f = csv.writer(open("./aws_logs/security_group.csv", "w", newline=''))
f.writerow(["ResourceType", "ResourceId", "Region"])
for unused_sg_detail in unused_sg_detail:
f.writerow([unused_sg_detail["ResourceType"],
unused_sg_detail["ResourceId"],
unused_sg_detail["Region"]])
unused_resource_count[function] = sg_count
def classic_loadbalancer(function, credentials, unused_resource_count, region_list):
print('Scanning Classic Load balancers')
elb_count = 0
unused_elb_detail = []
for region in region_list:
try:
classic_lb = boto3.client('elb', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'], region_name=region)
paginated_data=[]
elb_paginator = classic_lb.get_paginator('describe_load_balancers')
for load_balancers in elb_paginator.paginate():
paginated_data.extend(load_balancers['LoadBalancerDescriptions'])
for elb_detail in paginated_data:
instance_health_status = []
instance_data = classic_lb.describe_instance_health(LoadBalancerName=elb_detail['LoadBalancerName'])['InstanceStates']
for instance in instance_data:
instance_health_status.append(instance['State'])
if 'InService' not in instance_health_status:
unused_elb_detail.append({'ResourceType':'AWS::ElasticLoadBalancing::LoadBalancer','ResourceId':elb_detail['LoadBalancerName'],'Region':region})
elb_count+=1
except:
pass
if elb_count:
unused_elb_detail = json.loads(json.dumps(unused_elb_detail))
f = csv.writer(open("./aws_logs/classic_loadbalancer.csv", "w", newline=''))
f.writerow(["ResourceType", "ResourceId", "Region"])
for unused_elb_detail in unused_elb_detail:
f.writerow([unused_elb_detail["ResourceType"],
unused_elb_detail["ResourceId"],
unused_elb_detail["Region"]])
unused_resource_count[function] = elb_count
def app_nw_gateway_loadbalancer(function, credentials, unused_resource_count, region_list):
print('Scanning Application/Network/Gateway Load balancers')
elbv2_count = 0
unused_elbv2_detail = []
for region in region_list:
try:
elbv2 = boto3.client('elbv2', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'], region_name=region)
paginated_data=[]
elbv2_paginator = elbv2.get_paginator('describe_load_balancers')
for load_balancers in elbv2_paginator.paginate():
paginated_data.extend(load_balancers['LoadBalancers'])
for elbv2_detail in paginated_data:
target_health_status = []
try:
target_group_detail = elbv2.describe_target_groups(LoadBalancerArn=elbv2_detail['LoadBalancerArn'])['TargetGroups']
for target_group in target_group_detail:
target_group_health = elbv2.describe_target_health(TargetGroupArn=target_group['TargetGroupArn'])['TargetHealthDescriptions']
for target in target_group_health:
target_health_status.append(target['TargetHealth']['State'])
except:
pass
if 'healthy' not in target_health_status:
unused_elbv2_detail.append({'ResourceType':'AWS::ElasticLoadBalancingV2::LoadBalancer', 'LoadBalancer_Type':elbv2_detail['Type'], 'ResourceId':elbv2_detail['LoadBalancerName'],'Region':region})
elbv2_count+=1
except:
pass
if elbv2_count:
unused_elbv2_detail = json.loads(json.dumps(unused_elbv2_detail))
f = csv.writer(open("./aws_logs/app_nw_gateway_loadbalancer.csv", "w", newline=''))
f.writerow(["ResourceType", "LoadBalancer_Type", "ResourceId", "Region"])
for unused_elbv2_detail in unused_elbv2_detail:
f.writerow([unused_elbv2_detail["ResourceType"],
unused_elbv2_detail["LoadBalancer_Type"],
unused_elbv2_detail["ResourceId"],
unused_elbv2_detail["Region"]])
unused_resource_count[function] = elbv2_count
def iam_user(function, credentials, unused_resource_count, region_list):
print('Scanning IAM Users')
iamuser_count = 0
unused_iamuser_detail = []
try:
iam = boto3.resource('iam', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'])
iam_client = boto3.client('iam', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'])
iamuser_data = list(iam.users.all())
for user in iamuser_data:
if not user.password_last_used and not iam_client.list_access_keys(UserName=user.name)['AccessKeyMetadata']:
unused_iamuser_detail.append({'ResourceType':'AWS::IAM::User', 'ResourceId': user.name, 'Region':'Global'})
iamuser_count += 1
except:
pass
if iamuser_count:
unused_iamuser_detail = json.loads(json.dumps(unused_iamuser_detail))
f = csv.writer(open("./aws_logs/iam_user.csv", "w", newline=''))
f.writerow(["ResourceType", "ResourceId", "Region"])
for unused_iamuser_detail in unused_iamuser_detail:
f.writerow([unused_iamuser_detail["ResourceType"],
unused_iamuser_detail["ResourceId"],
unused_iamuser_detail["Region"]])
unused_resource_count[function] = iamuser_count
def iam_group(function, credentials, unused_resource_count, region_list):
print('Scanning IAM Groups')
iamgroup_count = 0
unused_iamgroup_detail = []
try:
iam = boto3.resource('iam', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'])
iam_client = boto3.client('iam', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'])
iamgroup_data = list(iam.groups.all())
for group in iamgroup_data:
if not iam_client.get_group(GroupName=group.name)['Users']:
unused_iamgroup_detail.append({'ResourceType':'AWS::IAM::Group', 'ResourceId': group.name, 'Region':'Global'})
iamgroup_count += 1
except:
pass
if iamgroup_count:
unused_iamgroup_detail = json.loads(json.dumps(unused_iamgroup_detail))
f = csv.writer(open("./aws_logs/iam_group.csv", "w", newline=''))
f.writerow(["ResourceType", "ResourceId", "Region"])
for unused_iamgroup_detail in unused_iamgroup_detail:
f.writerow([unused_iamgroup_detail["ResourceType"],
unused_iamgroup_detail["ResourceId"],
unused_iamgroup_detail["Region"]])
unused_resource_count[function] = iamgroup_count
def main(arg):
access_key = arg.accessKey
secret_key = arg.secretKey
region_list = []
unused_resource_details = {}
try:
print("Connecting to AWS account ")
session = boto3.session.Session(aws_access_key_id=access_key, aws_secret_access_key=secret_key)
except:
print("\033[1;31;40m ""Please do Check for Credentials provided or Internet Connection and Try Again\n")
quit()
iam = session.client('sts')
account_id = iam.get_caller_identity()["Account"]
print("Successfully connected to AWS account", account_id)
print("Scanning for unused resources across all available regions.")
print("Wait for few minutes...\n")
function_list= [ ebs_volume, elastic_ip, network_interface, vpc, subnet, security_group, classic_loadbalancer, app_nw_gateway_loadbalancer,
iam_user, iam_group ]
print("Collecting list of enabled region")
available_regions = session.client('ec2',region_name="us-east-1")
enabled_regions = available_regions.describe_regions()['Regions']
for region in enabled_regions:
region_list.append(region['RegionName'])
manager = multiprocessing.Manager()
unused_resource_count = manager.dict()
credentials = manager.dict()
credentials['access_key'] = access_key
credentials['secret_key'] = secret_key
credentials['account_id'] = account_id
jobs = []
try:
os.mkdir("./aws_logs")
except:
pass
for function in function_list:
try:
p = multiprocessing.Process(target=function, args=(function, credentials, unused_resource_count, region_list))
jobs.append(p)
p.start()
except:
print("Exception occurred while creating processes. Please try again later!")
quit()
if jobs:
for process in jobs:
try:
process.join()
except:
print("Exception occurred while joining processes. Please try again later!")
quit()
os.chdir('./aws_logs')
writer = pd.ExcelWriter('unused_resources.xlsx')
all_files = glob.glob("*.csv")
for f in all_files:
df = pd.read_csv(f)
df.to_excel(writer,sheet_name=f.split('.')[0], index=False)
writer.save()
for f in all_files:
os.remove(f)
print("Completed account scan")
# Updating Resource Count Object
unused_resource_details.update({ 'AWS::EC2::Volume': unused_resource_count[ebs_volume],
'AWS::EC2::EIP': unused_resource_count[elastic_ip],
'AWS::EC2::NetworkInterface': unused_resource_count[network_interface],
'AWS::EC2::VPC': unused_resource_count[vpc],
'AWS::EC2::Subnet': unused_resource_count[subnet],
'AWS::EC2::SecurityGroup': unused_resource_count[security_group],
'AWS::ElasticLoadBalancing::LoadBalancer': unused_resource_count[classic_loadbalancer],
'AWS::ElasticLoadBalancingV2::LoadBalancer': unused_resource_count[app_nw_gateway_loadbalancer],
'AWS::IAM::User': unused_resource_count[iam_user],
'AWS::IAM::Group': unused_resource_count[iam_group]
})
# Showing Resource Distribution
print("\nUnused Resources in the Account:")
unused_resource_count = 0
for key, value in sorted(unused_resource_details.items(), key=lambda x: x[1], reverse=True):
if value != 0:
print("\t{} : {}".format(key, value))
unused_resource_count+=value
print("\n\nSummary:")
print("\tTotal Unused Resources:", unused_resource_count)
print("\n\nDetailed unused resource information can be found at: aws_logs/unused_resources.xlsx")
if(__name__ == '__main__'):
arg_parser = argparse.ArgumentParser(prog='unused_aws_resources',
usage='%(prog)s [options]',
description='Count AWS resources')
# Add the arguments
arg_parser.add_argument('--accessKey',
type=str,
required=True,
help='AWS Access Key')
arg_parser.add_argument('--secretKey',
type=str,
required=True,
help='AWS Secret Key')
# Execute the parse_args() method
args = arg_parser.parse_args()
main(args)