Invoke a lambda function with deployment using serverless framework

对着背影说爱祢 提交于 2019-12-07 05:04:35

问题


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


回答1:


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




回答2:


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"


来源:https://stackoverflow.com/questions/52525042/invoke-a-lambda-function-with-deployment-using-serverless-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!