gh9
gh9

Reputation: 10703

AWS Lambda finishes trigger another lambda

When I have an AWS lambda finish, I want to trigger another lambda to run. The first lambda lets call X, is full of asynch code and I would rather not mess with that. I thought I could use cloudwatch to say when X is done call lambda Y. But I cannot find out how to do that.

Can someone help me figure out how to run 1 lambda when another lambda finishes? thank you very much

Edit

It has been suggested that I wrap all the asynch calls and use an SDK, it isnt feasible to re-write this code to use a new sdk. What I am looking for is a way to monitor when a lambda is done and then call another lambda. More of an observer pattern instead of a notifier pattern.

Upvotes: 1

Views: 1788

Answers (3)

Vjerci
Vjerci

Reputation: 580

You could do a quick-fix by wraping callback function to trigger your lambda.

let wrap = (originalFunction) => {
    return (event, context, callback) => {
        let overwriteCallback = (err, data) => {
            // do your stuff here
            // publish to sns to run your lambda
            // or directly run your lambda
            // then finally run callback

            callback(err, data)
        }
        originalFunction(event, context, overwriteCallback);
    }
}

module.exports = wrap((event, context, callback) => {
    //original mess we don't want to touch
})

If it is older you probably also want to overwrite context.succeed(); context.fail(); context.done()

You can find the documentation about those methods here: https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-using-old-runtime.html

Upvotes: 0

m_callens
m_callens

Reputation: 6360

The aws-sdk allows you to instantiate a new Lambda object, and assuming you know the ARN of the second lambda you wish to execute, you can invoke that after your asynchronous code has complete.

Something similar to this for your given code in the first lambda should work...

const AWS = require('aws-sdk')
const lambda = new AWS.Lambda(/* Options object, look in docs */)

asynchronousOperations()
    .then(() => {
        lambda.invoke({
            FunctionName: SECOND_LAMBDA_ARN,
            InvocationType: TYPE,
            Payload: JSON.stringify(PAYLOAD_OBJ_IF_YOU_HAVE_ONE),
            // other options you may want
        })
    })

Upvotes: 1

clay
clay

Reputation: 6017

Have your first Lamba send a message on SNS. Then configure CloudWatch to monitor SNS, the result being to run your second Lambda.

Upvotes: 0

Related Questions