Reputation: 803
Is there a way to invoke a lambda function immediately after deployment using serverless framework. This function just creates the SNS Application, which is required to be done once only during setup.
I can use serverless deploy stage && serverless invoke --function functionName
but that won't tear down the setup if the function fails.
I want it to be deployed as part of setup.
Thanks
Upvotes: 13
Views: 7106
Reputation: 803
Hooks can be added to the lifecycle events of the Serverless framework.
I used serverless-plugin-scripts plugin(https://www.npmjs.com/package/serverless-plugin-scripts) to invoke custom jobs after deployment and removal of stack.
Here is an example -
custom:
scripts:
hooks:
'deploy:finalize': sls invoke -f functionName &&
'remove:remove': npm run scriptName && sls invoke -f anotherFunctionName
Now, after successful deployment via serverless deploy
, sls invoke -f functionName
is triggered.
Similarly, on removal using serverless remove
, npm run scriptName && sls invoke -f anotherFunctionName
executes.
Complete list of Serverless framework's Lifecycle events / commands is available here - https://gist.github.com/HyperBrain/50d38027a8f57778d5b0f135d80ea406
Upvotes: 29
Reputation: 81
Not sure if this entirely fits your needs, but I've had success with configuring a Lambda function with a CloudWatch event that will trigger on CloudFormation API calls.
You'll need CloudTrail enabled to do this.
You could probably limit the function's execution to specific stacks (probably using the resources
attribute in the CloudTrail event)
...
functions:
stack-deployment-function:
handler: stack-deployment-function.handler
description: Lambda function triggered by Stack changes/deployments
timeout: 300
environment:
FOO: bar
events:
- cloudwatchEvent:
name: ${self:service}-${opt:stage, self:provider.stage}-stack-deployment-function
description: 'Updates XYZ after CloudFormation update'
event:
source:
- "aws.cloudformation"
detail-type:
- "AWS API Call via CloudTrail"
detail:
eventName:
# Need to call DescribeStacks in Lambda to confirm successful deployment before making any changes
- "UpdateStack"
- "CreateStack"
Upvotes: 6