Cloudformation 与 Lambda 自定义资源错误 - Python

问题描述

我一直在考虑通过使用来自 CloudFormation (CF) 的 Lambda 来开发一些自定义资源,并且一直在考虑使用自定义资源助手,但它开始正常,然后 CF 堆栈花了很长时间来创建或删除。当我检查云监视日志时,我注意到在我的 Lambda 中运行 create 或 cloud 函数后出现错误

[7cfecd7b-69df-4408-ab12-a764a8bf674e][2021-02-07 12:41:12,535][ERROR] send(..) 执行 requests.put(..) 失败: 在记录中找不到格式字段:'requestid'

我注意到其他一些人也有这个问题,但没有解决。我使用了下面链接中的通用代码,我的自定义代码可以工作并完成,但看起来像是将更新传递给 CF。我浏览了 crhelper.py,我能找到的关于 'requestid' 的唯一参考是:

logfmt = '[%(requestid)s][%(asctime)s][%(levelname)s] %(message)s \n'
mainlogger.handlers[0].setFormatter(logging.Formatter(logfmt))
return logging.LoggerAdapter(mainlogger,{'requestid': event['RequestId']})

Reference

解决方法

要了解您遇到的错误,我们需要查看您正在执行的操作的可重现代码示例。请注意,每次在自定义资源操作上出现某种错误时,可能需要很长时间才能完成,正如您所注意到的。

但是,对于您正在使用的原始自定义资源助手,有一个很好的替代方案,并且根据我的经验,这非常有效,同时保持代码更简单(由于具有良好的抽象级别)并遵循最佳实践。这是 自定义资源助手框架,如 this AWS 博客中所述。

您可以在 github here 上找到有关实现的更多详细信息。

基本上,在下载所需的依赖项并将它们加载到您的 lambda 上后(这取决于您如何处理自定义 lambda 依赖项),您可以像这样管理您的自定义资源操作:

from crhelper import CfnResource
import logging

logger = logging.getLogger(__name__)
# Initialise the helper
helper = CfnResource()

try:
    ## put here your initial code for every operation
    pass
except Exception as e:
    helper.init_failure(e)


@helper.create
def create(event,context):
    logger.info("Got Create")
    print('Here we are creating some cool stuff')

@helper.update
def update(event,context):
    logger.info("Got Update")
    print('Here you update the things you want')

@helper.delete
def delete(event,context):
    logger.info("Got Delete")
    print('Here you handle the delete operation')


# this will call the defined function according the
# cloudformation operation that is running (create,update or delete)
def handler(event,context):
    helper(event,context)