在 CloudFormation 堆栈删除上执行 Lambda 函数
Execute Lambda Function on CloudFormation Stack delete
有没有办法触发 Lambda 函数 在给定 stack[=19= 时用于创建堆栈的同一个 CFN 模板中声明的] 正在 删除?
最好我想实现与 片段相反的东西(即:一个相对简单的解决方案,省略了创建 SNS 主题等的需要)。
提前感谢任何建议。最好的祝福! //M
您可以通过创建 CustomResource
并将其与您的 lambda 函数挂钩来实现所需的行为。
来自 documentation page:
With AWS Lambda functions and custom resources, you can run custom code in response to stack events (create, update, and delete)
lambda 函数需要对 Delete event 做出反应,因此必须编写它以允许这样做。
示例 lambda 函数源代码
这是 AWS lambda 函数配置的示例,它需要对删除事件做出反应:
import cfnresponse
def lambda_handler(event, context):
response = {}
if event['RequestType'] == 'Delete':
... # do stuff
response['output'] = ' Delete event.'
cfnresponse.send(event, context, cfnresponse.SUCCESS, response)
lambda 函数示例
这是 lambda 函数的 CloudFormation 片段:
"MyDeletionLambda": {
"Type": "AWS::Lambda::Function",
"Properties": {
"Code": {
"ZipFile": {
"Fn::Join": [
"\n",
[
"import cfnresponse",
"",
"def lambda_handler(event, context):",
" response = {}",
" if event['RequestType'] == 'Delete':",
" response['output'] = 'Delete event.'",
" cfnresponse.send(event, context, cfnresponse.SUCCESS, response)"
]
]
}
},
"Handler": "index.lambda_handler",
"Runtime": "python3.8"
}
}
}
示例自定义资源
这是自定义资源的 CloudFormation 片段:
"OnStackDeletion": {
"Type": "Custom::LambdaDependency",
"Properties": {
"ServiceToken": {
"Fn::GetAtt": [
"MyDeletionLambda",
"Arn"
]
}
}
}
有没有办法触发 Lambda 函数 在给定 stack[=19= 时用于创建堆栈的同一个 CFN 模板中声明的] 正在 删除?
最好我想实现与
提前感谢任何建议。最好的祝福! //M
您可以通过创建 CustomResource
并将其与您的 lambda 函数挂钩来实现所需的行为。
来自 documentation page:
With AWS Lambda functions and custom resources, you can run custom code in response to stack events (create, update, and delete)
lambda 函数需要对 Delete event 做出反应,因此必须编写它以允许这样做。
示例 lambda 函数源代码
这是 AWS lambda 函数配置的示例,它需要对删除事件做出反应:
import cfnresponse
def lambda_handler(event, context):
response = {}
if event['RequestType'] == 'Delete':
... # do stuff
response['output'] = ' Delete event.'
cfnresponse.send(event, context, cfnresponse.SUCCESS, response)
lambda 函数示例
这是 lambda 函数的 CloudFormation 片段:
"MyDeletionLambda": {
"Type": "AWS::Lambda::Function",
"Properties": {
"Code": {
"ZipFile": {
"Fn::Join": [
"\n",
[
"import cfnresponse",
"",
"def lambda_handler(event, context):",
" response = {}",
" if event['RequestType'] == 'Delete':",
" response['output'] = 'Delete event.'",
" cfnresponse.send(event, context, cfnresponse.SUCCESS, response)"
]
]
}
},
"Handler": "index.lambda_handler",
"Runtime": "python3.8"
}
}
}
示例自定义资源
这是自定义资源的 CloudFormation 片段:
"OnStackDeletion": {
"Type": "Custom::LambdaDependency",
"Properties": {
"ServiceToken": {
"Fn::GetAtt": [
"MyDeletionLambda",
"Arn"
]
}
}
}