crhelper简化了创建cloudformation自定义资源
crhelper的Python项目详细描述
自定义资源助手
简化最佳实践自定义资源创建,向cloudformation发送响应并提供异常、超时 捕获和详细的可配置日志记录。
功能
- 保证即使引发异常,cloudformation也会得到响应
- 在发生故障时,将有意义的错误返回给cloudformation堆栈事件
- 轮询使运行时间超过lambda 15分钟限制
- json日志记录,包括请求id、堆栈id和请求类型,以帮助跟踪与 特定云形成事件
- 捕获函数超时并向cloudformation发送故障响应
安装
安装到lambda函数的根文件夹中
cdmy-lambda-function/pipinstallcrhelper-t.
示例用法
from__future__importprint_functionfromcrhelperimportCfnResourceimportlogginglogger=logging.getLogger(__name__)# Initialise the helper, all inputs are optional, this example shows the defaultshelper=CfnResource(json_logging=False,log_level='DEBUG',boto_level='CRITICAL')try:## Init code goes herepassexceptExceptionase:helper.init_failure(e)@helper.createdefcreate(event,context):logger.info("Got Create")# Optionally return an ID that will be used for the resource PhysicalResourceId, # if None is returned an ID will be generated. If a poll_create function is defined # return value is placed into the poll event as event['CrHelperData']['PhysicalResourceId']## To add response data update the helper.Data dict# If poll is enabled data is placed into poll event as event['CrHelperData']helper.Data.update({"test":"testdata"})return"MyResourceId"@helper.updatedefupdate(event,context):logger.info("Got Update")# If the update resulted in a new resource being created, return an id for the new resource. CloudFormation will send# a delete event with the old id when stack update completes@helper.deletedefdelete(event,context):logger.info("Got Delete")# Delete never returns anything. Should not fail if the underlying resources are already deleted. Desired state.@helper.poll_createdefpoll_create(event,context):logger.info("Got create poll")# Return a resource id or True to indicate that creation is complete. if True is returned an id will be generatedreturnTruedefhandler(event,context):helper(event,context)
轮询
如果您需要的时间超过15分钟的最大运行时间,可以通过为
poll_create
、poll_update
或poll_delete
。当为create
/update
/delete
定义轮询函数时
函数不会向cloudformation发送响应,而是创建一个cloudwatch事件计划
每隔2分钟重新调用lambda函数。当调用该函数时,匹配的@helper.poll_
函数将
如果函数返回None
,则调度将再次运行。
两分钟后。完成后,返回physicalresourceid或True
以生成一个。日程安排是
删除并将响应发送回cloudformation。如果使用轮询,则以下附加IAM策略必须是
附加到函数的IAM角色:
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["lambda:AddPermission","lambda:RemovePermission","events:PutRule","events:DeleteRule","events:PutTargets","events:RemoveTargets"],"Resource":"*"}]}
学分
装饰器实现灵感来自https://github.com/ryansb/cfn-wrapper-python
日志实现的灵感来自https://gitlab.com/hadrien/aws_lambda_logging
许可证
此库是根据Apache2.0许可证授权的。