使用Lambda的自定义触发器更新AWS CloudFormation

时间:2017-03-24 14:22:37

标签: amazon-web-services lambda amazon-cloudformation

团队成员和我有一个CloudFormation堆栈,其中包含nodejs Lambda支持的自定义资源。

更新lambda / parameters / trigger后,我们希望Lambda首先删除它所创建的第三方资源,然后根据新参数创建新资源。

这是我们对lambda的exports.handler。

if (event.RequestType == "Delete") {
    console.log("Request type == Delete")
    var successCallback = function(event, context) {
        sendResponse(event, context, "SUCCESS");
    }
    doDeleteThings(event, context, successCallback);
} else if (event.RequestType == "Create") {
    console.log("request type == create")
    doCreateThings(event, context);
} else if (event.RequestType == "Update") {
    console.log("request type == update")
    var successCallback = function(event, context) {
        doCreateThings(event, context);
    }
    doDeleteThings(event, context, successCallback);
} else {
    sendResponse(event, context, "SUCCESS");
}

我们测试了代码,它适用于CloudFormation中的创建和删除,以及无堆栈模式下的创建,删除和更新(我们设置:event.RequestType = process.env.RequestType和sendResponse不执行通常的CloudFormation响应POSTing,但只是执行context.done()),但我们似乎无法使其在CloudFormation中进行更新。我开始认为我们误解了Lambda应该做什么'更新'。

我们以前从未能看到CloudFormation创建的Lambda函数的CloudWatch日志,这无济于事。

以下是CloudFormation模板的相对部分:

   "ManageThirdPartyResources": {
        "Type": "AWS::Lambda::Function",
        "Properties": {
            "Code": {
                "S3Bucket": "<bucketname>",
                "S3Key": "<zipname>.zip"
            },
            "Description": { "Fn::Join": ["", ["Use cloudformation to automatically create third party resources for the ", { "Ref": "ENV" }, "-", { "Ref": "AWS::StackName" }, " environment"]] },
            "Environment": {
                "Variables": {
                    <environment variables that will probably be the things changing.>
                }
            },
            "FunctionName": {
                "Fn::Join": ["_", [{ "Ref": "AWS::StackName" }, "ManageThirdPartyResources"]]
            },
            "Handler": "index.handler",
            "Role": "<role>",
            "Runtime": "nodejs4.3",
            "Timeout": 30
        }
    },
    "ThirdPartyResourcesTrigger": {
        "Type": "Custom::ThirdPartyResourcesTrigger",
        "Properties": {
            "ServiceToken": { "Fn::GetAtt": ["ManageThirdPartyResources", "Arn"] }
        }
    },

谢谢!

1 个答案:

答案 0 :(得分:5)

如果其中一个 属性发生更改,则会在Custom::ThirdPartyResourcesTrigger上触发更新。如果Lambda函数的属性发生更改,则会触发Custom::ThirdPartyResourcesTrigger上的更新。

因此,如果要在Custom::ThirdPartyResourcesTrigger上触发更新,则必须修改其属性。例如,您可以向名为ThirdPartyResourcesTrigger的{​​{1}}添加属性,每当您更改ThingName的值时,将使用ThingName请求类型调用您的Lambda:< / p>

Update

对于日志记录,请确保Lambda函数承担的IAM角色具有CloudWatch日志所需的权限:

"ThirdPartyResourcesTrigger": {
    "Type": "Custom::ThirdPartyResourcesTrigger",
    "Properties": {
        "ServiceToken": { "Fn::GetAtt": ["ManageThirdPartyResources", "Arn"] },
        "ThingName": "some value"
    }
},