【问题标题】:Code times out when trying to run as a lambda function in AWS尝试在 AWS 中作为 lambda 函数运行时代码超时
【发布时间】:2019-07-06 03:14:15
【问题描述】:

以下是我的代码,我希望有人可以帮助我清理代码并使其更高效。基本上,代码应该遍历我的 AWS 账户中的所有卷,然后列出所有未标记的卷,然后发送一封电子邮件。但是,在 AWS 中将其作为 lambda 函数运行时会超时,但如果我在本地运行它,则需要 30 多分钟才能完成(但它确实完成了)。我确定它会遍历它不需要的东西。

另外,如果我打印 ec2_instances 列表,我可以看到重复的值,所以我只想拥有唯一的值,这样它就不会为每个 ec2 实例重复脚本。

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 = "xxx@xxx.com"
mail_to = 'xxx@xxx.com'

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', 'xx')
    server.sendmail(mail_from, mail_to.split(','), msg.as_string())
    server.quit()
    print('Email sent')
except SMTPException:
    print('ERROR! Unable to send mail')

【问题讨论】:

  • 乍一看,我认为您可以开始使用 boto3 资源,而不是文档建议的 client。那里的功能更快,更适合开箱即用。从重构这个开始,即检查评论有 7 个赞成票:stackoverflow.com/questions/34002826/list-ec2-volumes-in-boto
  • 什么是“unique_list”和“instance”?您遍历“unique_list”并将每个项目分配为“实例”,但随后不使用任何一个
  • unique_list 是我用来测试的。感谢您指出了这一点。我已经编辑了代码。
  • 有人能帮忙吗?我已经设法创建了一个只有唯一 instanceid 的新列表(更新代码以反映这一点),但代码仍然需要永远运行(有人告诉我这可能是因为 describe_instances)以及何时运行最终完成后,它会多次向我发送一封电子邮件,其中包含同一实例的信息

标签: python amazon-web-services aws-lambda


【解决方案1】:

Lambda 函数的时间限制为 15 分钟。这就是超时的原因 - 如果您需要更长时间地运行脚本,请查看 AWS Fargate

【讨论】:

  • Fargate 目前不适合我们。我知道 Lambda 的超时时间为 15 分钟,但我认为如果我的脚本花费的时间比这更长,我的脚本可能有问题,这就是我寻求帮助的原因
猜你喜欢
  • 2017-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-17
  • 2019-06-17
相关资源
最近更新 更多