【问题标题】:Execute Lambda Function on CloudFormation Stack delete在 CloudFormation 堆栈上执行 Lambda 函数删除
【发布时间】:2022-01-27 23:19:12
【问题描述】:

当给定的堆栈删除触发在用于创建堆栈的相同CFN模板中声明的Lambda函数/强>?
最好我想实现与THIS sn-p 有点相反的实现(即:一个相对简单的解决方案,省略了例如创建 SNS 主题等的需要)。
提前感谢任何建议。最好的祝福! //M

【问题讨论】:

  • 我的解决方案对您有用吗?

标签: amazon-web-services aws-lambda stack amazon-cloudformation aws-cloudformation-custom-resource


【解决方案1】:

您可以通过创建 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"
      ]
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-27
    • 2021-03-15
    • 2019-09-01
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 2017-10-20
    相关资源
    最近更新 更多