Is it possible to start lambda when creating from a CloudFormation template

I tried to create a lambdas suite using cloudformation. I want lambdas to fire after they are created. I have seen on various blogs to create a trigger for s3 or sns , but none of them can start lambda after it is created. Any options?

+14
amazon-cloudformation aws-lambda
source share
4 answers

Yes it is possible. Here are a few options:

  1. Manually create an SNS theme . Add AWS::SNS::Subscription to your stack using the lambda function as the TopicArn Endpoint and the SNS theme as the TopicArn . When creating / updating a stack, configure stack event notifications to be sent to this SNS section.

  2. Add a custom resource referencing the lambda function that will be called upon creation.

    • If you need the lambda function to be called after creating a specific resource, add the DependsOn attribute to the user resource that refers to the resource that you want to make sure that it was created first before the function was called.
    • In order for the user resource to be created successfully (and not cause a crash / rollback on your stack), you will need to adapt your Lambda function to support the CloudFormation request / response format (see Link to the user resource ).
    • This option will call the lambda function while the stack status is still CREATE_IN_PROGRESS , because the user resource is part of the stack itself.
    • The lambda function will also be called again when the stack (and the associated user resource) is deleted. This should be handled correctly by your lambda function, otherwise your stack might be stuck in the DELETE_FAILED state.
  3. Add a link to the Lambda function to the output of the stack , then write a simple script that creates the stack and then manually calls the Lambda function.

+22
source share

For those looking for a similar workaround.

CloudWatch is capable of catching CloudFormation API calls that are “CreateStack”, “UpdateStack” and “DeleteStack”, stack states such as “Create_complete” or “Complete_Rollback” are not available, which means that such state changes cannot be triggered by the lambda.

The workaround is SNS, the stacks can send SNS notifications (in the preset when creating the stack), and SNS can choose to start lambda, however you cannot choose for certain states. Thus, the lambda function performs the task to find out what state is in the "message" of the event content. Everything, just coding.

+1
source share

You have the opportunity to notify the SNS theme, and you can create a lambda that listens to the theme, so the workflow will be as follows: launch Cloudformation → SNS theme → Lambda.

0
source share

The following pattern should call a lambda:

"InvokeLambda": {"Type": "Custom :: InvokeLambda", "Version": "1.0", "Properties": {"ServiceToken": {"Fn :: GetAtt": ["InitFunction", "Arn"] }}},

0
source share

All Articles