Search code examples
amazon-web-servicesaws-sdk-jsaws-sdk-nodejs

How to add a trigger to lambda function via SDK or CDK


I'm trying to add a trigger to a lambda function, using the UI, I'm able to select trigger type "Cloud Watch".

enter image description here

Browser (Chrome) network tab, reveals this function being called.

fetch(
    "https://console.aws.amazon.com/lambda/services/ajax?operation=createRelation&locale=en",
    {
      headers: {
        accept: "application/json, text/plain, */*",
        "accept-language": "en-US,en;q=0.9",
        "content-type": "application/json",
      },
      body: {
        type: "trigger",
        source: "arn:aws:logs:us-east-1:7669313121:log-group:api-gateway-testAPI:*",
        target: "arn:aws:lambda:us-east-1:7669313121:function:datadog-ForwarderStack-SSQ7M5T3R0FL-Forwarder-ex9N3F3QIExf",
        data: '{"enabled":true,"identifier":"arn:aws:logs:us-east-1:766931360739:log-group:api-gateway-testAPI:*","filterName":"apigwLogs"}',
        operation: "createRelation",
      },
      method: "POST",
    }
  );

I haven't been able to find an equivalent function via SDK or CDK, I'm wondering if it's an acceptable practice to use the above function to achieve this task.


Solution

  • When you want to select a ClouWatch log stream as a trigger for a Lambda function, AWS creates a subscription under the hood.

    CDK supports subscriptions and destinations for log streams by creating a SubscriptionFilter.

    From the JavaScript SDK (V3) you can create subscription filters using PutSubscriptionFilterCommand.