How to pass values to a Lambda function in CloudWatch?

samcorcos picture samcorcos · Mar 22, 2017 · Viewed 14.4k times · Source

What's the best way to wrap functions in a way that handles a ping from a CloudWatch timer? For example, take the lambda function below:

export const fn = (event, context, callback) => {
  const { year, make, model, } = event.queryStringParameters

  return otherFn({ year, make, model, })
    .then(res => response(callback, res))
    .catch(err => console.log(err))
}

If I ping the function, it will error because there are no queryStringParameters on the CloudWatch request. Technically, this will still do the job of keeping the Lambda function warm (which is my goal), but I don't want to have a needlessly-long list of errors.

I noticed that CloudWatch allows you to include inputs that (presumably) are passed to a Lambda function:

configure input

What's the smartest way to wrap the function above so that it can accept a ping? Ideally it would look like this:

export const fn = (event, context, callback) => {
  if (event.ping) return ping(callback) // the ping function is an import to stay DRY
  const { year, make, model, } = event.queryStringParameters

  return otherFn({ year, make, model, })
    .then(res => response(callback, res))
    .catch(err => console.log(err))
}

Where I would pass some JSON that allows me to alter the event, such as:

{ "ping": true }

I've read through the documentation for the inputs, but it's not at all clear to me what the various input types mean or how to use them...

Answer

user818510 picture user818510 · Apr 29, 2017

If you select input option Constant (JSON text), an input box should appear just below. You need to enter the json {"ping": true}. Your function will get the json as the event object and you can access event.ping just like your code.

If you are using the serverless framework, instead of doing this in AWS console, you can add an schedule event for your function. This would be in addition to your existing http event. You can add the ping: true parameter under the input section of the scheduled event like this:

scheduledFunction:
  handler: index.handler
  events:
    - schedule:
        rate: rate(1 minute)
        enabled: true
        input:
          ping: true

This will create and enable the cloudwatch log event with the specified schedule and send the input parameter ping in the event object.