Enable/Disable AWS Lambda Triggers Programmatically by Invoking an API

Lambda functions can be triggered by a number of sources by creating event source mappings, but if you need to enable/disable these mappings programmatically, to control when the Lambda function triggers, the most straightforward way is to call Lambda’s UpdateEventSourceMapping API with the { "Enabled": true/false } request body. If however:

  • you don’t want to introduce the AWS SDK into your codebase
  • or wish to avoid the Sig v4 auth process
  • or you’d like a new API for this in your existing backend API collection
  • or just prefer to or are required to use an HTTP GET API, instead of the PUT that Lambda provides

then Amazon API Gateway is the way to go. This post explains how to set up an API in API Gateway to enable/disable your Lambda triggers.

Before you begin, you need the UUID of the event source mapping you wish to enable/disable. Use the AWS CLI to get this (it isn’t shown on the UI):

> aws lambda list-event-source-mappings --function-name my-func
{
    "EventSourceMappings": [
        {
            "UUID": "b962dcee-173c-47r1-9600-5c6d81catf85",
            "BatchSize": 1,
            "EventSourceArn": "arn:aws:sqs:us-east-1:123456789012:my-queue",
            "FunctionArn": "arn:aws:lambda:us-east-1:123456789012:function:my-func",
            "LastModified": 1595058588.141,
            "State": "Enabled",
            "StateTransitionReason": "USER_INITIATED"
        }
    ]
}

Next, either create a new API in API Gateway or add a resource & a GET method to your existing API. Configure it as shown below. The UUID you got above is highlighted below:

The execution role shown above must allow API Gateway to invoke Lambda APIs.

Scroll further down & provide this mapping template:

Save this config & test the API:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.