使用Lambda自定义资源的Cloudformation错误Python

2024-10-16 20:45:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

[7cfecd7b-69df-4408-ab12-a764a8bf674e][2021-02-07 12:41:12,535][ERROR] send(..) failed executing requests.put(..): Formatting field not found in record: '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


Tags: lambda函数代码cloud堆栈logging错误create
1条回答
网友
1楼 · 发布于 2024-10-16 20:45:34

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

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

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

基本上,在下载所需的依赖项并将其加载到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)

相关问题 更多 >