Python Forum
AWS lambda script help - Listing untagged volumes
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
AWS lambda script help - Listing untagged volumes
#1
Below is my code and I am hoping someone can help me with the cleaning up the code and making it more effiencient. Basically, the code should iterate through all the volumes in my AWS account and then list all untagged volumes and then send out an email. However, it times out when running it as a lambda function in AWS (set to max 15 mins) but if i run it locally, it will take over 30 mins to complete (however it does complete).

import logging
import boto3
from smtplib import SMTP, SMTPException
from email.mime.text import MIMEText

logger = logging.getLogger()
logger.setLevel(logging.INFO)

session = boto3.Session(profile_name="prod")
client = session.client('ec2')

untagged_volumes = []
detached_volumes = []
ec2_instances = []

response = client.describe_volumes()

for volume in response['Volumes']:
    if 'Tags' in str(volume):
        continue
    else:
        if 'available' in str(volume):
            detached_volumes.append(volume['VolumeId'])
        else:
            untagged_volumes.append(volume['VolumeId'])
            untagged_volumes.append(volume['Attachments'][0]['InstanceId'])
            ec2_instances.append(volume['Attachments'][0]['InstanceId'])

unique_instances = list(set(ec2_instances))

# Create the msg body.
msg_body_list = []
for instance in unique_instances:
    desc_instance = client.describe_instances()

    # append to the msg_body_list the lines that we would like to show on the email
    msg_body_list.append("VolumeID: {}".format(desc_instance['Reservations'][0]['Instances'][0]['BlockDeviceMappings'][0]['Ebs']['VolumeId']))
    msg_body_list.append("Attached Instance: {}".format(desc_instance['Reservations'][0]['Instances'][0]['InstanceId']))

    # if there are tags, we will append it as singles lines as far we have tags
    if 'Tags' in desc_instance['Reservations'][0]['Instances'][0]:
        msg_body_list.append("Tags:")
        for tag in desc_instance['Reservations'][0]['Instances'][0]['Tags']:
            msg_body_list.append("    Key: {} | Value: {}".format(tag['Key'], tag['Value']))
    # in case we don't have tags, just append no tags.
    else:
        msg_body_list.append("Tags: no tags")
        msg_body_list.append("--------------------")

# send email
mail_from = "[email protected]"
mail_to = '[email protected]'

msg = MIMEText("\n".join(msg_body_list))
msg["Subject"] = "EBS Tagged Instance Report for"
msg["From"] = mail_from
msg["To"] = mail_to

try:
    server = SMTP('xxx.xxx.xxx.xxx', 'xxx')
    server.sendmail(mail_from, mail_to.split(','), msg.as_string())
    server.quit()
    print('Email sent')
except SMTPException:
    print('ERROR! Unable to send mail')
When the script finally does complete and send the email, I only get the same instanceid listed loads of times with all information related to taht, so its not even iterating throught the unique_instances list. just picks the first one and repeats the process for that.

Any help would be appreciated.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Listing directories (as a text file) kiwi99 1 834 Feb-17-2023, 12:58 PM
Last Post: Larz60+
  Read directory listing of files and parse out the highest number? cubangt 5 2,338 Sep-28-2022, 10:15 PM
Last Post: Larz60+
  Multithreaded file transfer from multiple volumes skoobi 2 1,138 Jul-28-2022, 07:52 AM
Last Post: skoobi
  Listing All Methods Of Associated With A Class JoeDainton123 3 2,339 May-10-2021, 01:46 AM
Last Post: deanhystad
  Listing files with glob. MathCommander 9 4,924 Oct-26-2020, 02:04 AM
Last Post: MathCommander
  Listing data from a list ebolisa 1 1,736 Sep-29-2020, 02:24 PM
Last Post: DeaD_EyE
  Listing Attributes of Objects & Classes JoeDainton123 4 2,350 Aug-28-2020, 05:27 AM
Last Post: ndc85430
  Listing groups tharpa 2 2,571 Nov-26-2019, 07:25 AM
Last Post: DeaD_EyE
  Script for untagged resources in aws jutler 1 4,270 Jan-15-2019, 06:30 PM
Last Post: hbknjr
  CSV import results in listing of all letters of elements Bigshow23 3 3,790 May-23-2017, 08:00 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020