Skip to content

Add Lambda handler wrapper for SNS-based custom resources #208

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 23, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions cfn/wrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,22 @@ package cfn

import (
"context"
"encoding/json"
"errors"
"log"
"net/http"

"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambdacontext"
)

// CustomResourceLambdaFunction is a standard form Lambda for a Custom Resource.
type CustomResourceLambdaFunction func(context.Context, Event) (reason string, err error)

// SNSCustomResourceLambdaFunction is a standard form Lambda for a Custom Resource
// that is triggered via a SNS topic.
type SNSCustomResourceLambdaFunction func(context.Context, events.SNSEvent) (reason string, err error)

// CustomResourceFunction is a representation of the customer's Custom Resource function.
// LambdaWrap will take the returned values and turn them into a response to be sent
// to CloudFormation.
Expand Down Expand Up @@ -73,3 +80,24 @@ func lambdaWrapWithClient(lambdaFunction CustomResourceFunction, client httpClie
func LambdaWrap(lambdaFunction CustomResourceFunction) (fn CustomResourceLambdaFunction) {
return lambdaWrapWithClient(lambdaFunction, http.DefaultClient)
}

// LambdaWrapSNS wraps a Lambda handler with support for SNS-based custom
// resources. Usage and purpose otherwise same as LambdaWrap().
func LambdaWrapSNS(lambdaFunction CustomResourceFunction) SNSCustomResourceLambdaFunction {
inner := LambdaWrap(lambdaFunction)
return func(ctx context.Context, event events.SNSEvent) (reason string, err error) {
if len(event.Records) != 1 {
err = errors.New("expected exactly 1 incoming record")
return
}

message := event.Records[0].SNS.Message

var innerEvent Event
if err = json.Unmarshal([]byte(message), &innerEvent); err != nil {
return
}

return inner(ctx, innerEvent)
}
}