python - 尝试在 AWS 中作为 lambda 函数运行时代码超时

标签 python amazon-web-services aws-lambda

下面是我的代码,我希望有人可以帮助我清理代码并使其更加高效。基本上,代码应该遍历我的 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')

最佳答案

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

关于python - 尝试在 AWS 中作为 lambda 函数运行时代码超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54650676/

相关文章:

python - 如何获取光标所在的整行文本

python - 为什么没有打印任何行并且估计系数为 NaN?

python - 模块未找到错误 : No module named 'CairoSVG'

angularjs - 如何在不知道Content-Type的情况下生成AWS S3预签名URL请求?

amazon-web-services - 如何定期运行在 CDK 中创建的 Lambda?

ios - 使用 AWS SDK 在 Swift 中包含未找到 sqlite3.h 的非模块化 header 和文件

aws-lambda - 在 SAM json 中将授权者添加到 api 网关

amazon-web-services - libtensorflow.so : cannot open shared object file: No such file or directory

python - 如何在Python中使用tesseract ocr获取结构形式的信息?

node.js - 使用 AWS Lambda 函数解析来自 Twilio 多部分/表单数据响应的传真数据时 PDF 损坏