0
votes

I am trying to write a Lambda function in C# (.NET Core) that will handle when a CloudWatch event occurs in my account. I am using the Serverless Application Framework ( https://www.serverless.com/ ) and have previously been successful with writing the handler code to respond to ApiGateway Requests/events. For the ApiGateway request handlers, the methods signature always had the same two parameters:

public APIGatewayProxyResponse SampleHandler(RequestAPIGatewayProxyRequest request, ILambdaContext context)

Per the docs ( https://docs.aws.amazon.com/lambda/latest/dg/csharp-handler.html ), the first parameter is defined as the "inputType" and is typically specific to the event that trips the function and the second parameter is the generic Lambda function context information. Currently, I've been unsuccessful in finding the corresponding object type of a Cloudwatch event.

My serverless application framework YAML file has the event for wired up like so:

functions:
  NewRevision:
    handler:  CsharpHandlers::AwsDotnetCsharp.Handlers::NewDataExchangeSubscriptionRevision
    memorySize: 1024 # optional, in MB, default is 1024
    timeout: 20 # optional, in seconds, default is 6
    events:
      - cloudwatchEvent:
          event:
            source:
              - 'aws.dataexchange'
            detail-type:
              - 'Revision Published To Data Set'

My question is, does anyone know what the appropriate object type that should be used in the method signature for a CloudWatch event?

2

2 Answers

3
votes

From the Amazon.Lambda.CloudWatchEvents NuGet package you can use the CloudWatchEvent type. The trick is CloudWatchEvent is a generic class depending on the event source. There are some event detail types defined in the Amazon.Lambda.CloudWatchEvents but depending on your event type you might have to create a own POCO to be used for the generic parameter which has the fields you care about.

0
votes

You can just pass your own object you want to accept into the FunctionHandler signature:

Cloudwatch event input: {"RegionId":"EMEA"}

My code to accept object:

public class Payload
{
    public string RegionId { get; set; }
}

private static async Task Main(string[] args)
{
        Func<Payload, ILambdaContext, Task<string>> func = FunctionHandler;
        using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(func, new JsonSerializer()))
        using (var bootstrap = new LambdaBootstrap(handlerWrapper))
        {
            await bootstrap.RunAsync();
        }
    }
}

public async static Task<string> FunctionHandler(Payload payload, ILambdaContext context)
{
    // Do something
    return "{\"status\":\"Ok\"}";
}