您可以通过创建 CustomResource 并将其与您的 lambda 函数挂钩来实现所需的行为。
来自documentation page:
借助 AWS Lambda 函数和自定义资源,您可以运行自定义代码来响应堆栈事件(创建、更新和删除)
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 sn-p:
"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 sn-p:
"OnStackDeletion": {
"Type": "Custom::LambdaDependency",
"Properties": {
"ServiceToken": {
"Fn::GetAtt": [
"MyDeletionLambda",
"Arn"
]
}
}
}