Skip to content

Commit 22a507d

Browse files
committed
updated lambda fn implementation
1 parent db33a77 commit 22a507d

File tree

1 file changed

+17
-29
lines changed

1 file changed

+17
-29
lines changed

lambda_function.py

Lines changed: 17 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,25 @@
11
import boto3
22
import logging
33

4-
ec2 = boto3.client('ec2')
4+
ec2 = boto3.resource('ec2')
55

66
logger = logging.getLogger()
77
logger.setLevel(logging.INFO)
88

9-
# sns_client = boto3.client('sns')
10-
volumes = ec2.describe_volumes()
11-
129
def lambda_handler(event, context):
13-
unused_volumes = []
14-
for vol in volumes['Volumes']:
15-
if len(vol['Attachments']) == 0:
16-
vol1 = ("-----Unused Volume ID = {}------".format(vol['VolumeId']))
17-
unused_volumes.append(vol1)
18-
19-
#email
20-
# sns_client.publish(
21-
# TopicArn='<SNS Topic ARN>',
22-
# Subject='Warning - Unused Volume List',
23-
# Message=str(unused_volumes)
24-
# )
25-
26-
print("EBS vols to delete:")
27-
for vol in unused_volumes:
28-
print(vol)
29-
30-
return {
31-
"statusCode": 200,
32-
"isBase64Encoded": False,
33-
"headers": {
34-
"Content-Type": "application/json"
35-
},
36-
"body": {"unused_volumes": unused_volumes}
37-
}
10+
logger.info("identifying unattached volumes...")
11+
12+
vol_filter = [
13+
{'Name':'tag:AutoDelete', 'Values':['True']},
14+
{'Name': 'status','Values': ['available']}
15+
]
16+
17+
volumes = [v for v in ec2.volumes.filter(Filters=vol_filter)]
18+
19+
logger.info(f"volumes unattached: {volumes}")
20+
21+
for vol in volumes:
22+
logger.info(f"deleting volume: {vol.id}")
23+
vol.delete()
24+
25+
logger.info("unattached volumes deleted")

0 commit comments

Comments
 (0)