Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setup Lambda function to run a CloudFormation stack

Is it possible to run a CloudFormation stack whenever I get a specific SNS notification. Any suggestions how to achieve this scenario.

Whenever I get a specific SNS notification, a Lambda function should be triggered which will then launch a CloudFormation stack.

like image 824
Pushkar Avatar asked Sep 06 '17 12:09

Pushkar


People also ask

Can Lambda invoke CloudFormation?

AWS CloudFormation invokes your Lambda function asynchronously with an event that includes a callback URL. The function is responsible for returning a response to the callback URL that indicates success or failure. For the full response syntax, see Custom resource response objects.

How do you use Lambda function in CloudFormation?

The AWS::Lambda::Function resource creates a Lambda function. To create a function, you need a deployment package and an execution role. The deployment package is a . zip file archive or container image that contains your function code.

Can CloudFormation interact with Lambda?

Using AWS CloudFormation to deploy AWS Lambda functions provides a reliable, reproducible and version-able deployment mechanism. But while simple deployments are easily achieved, it can be challenging to produce templates that seamlessly deploy to any AWS Region supported by Lambda.

How do I launch a CloudFormation stack?

To create a stack on the CloudFormation consoleOpen the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation . Create a new stack by using one of the following options: Choose Create Stack. This is the only option if you have a currently running stack.


1 Answers

As you can access the AWS API from within AWS Lambda that's no problem at all. If you're using Python that could look like:

import boto3
cf_client = boto3.client('cloudformation')
cf_client.create_stack(
    StackName='your-stack',
    TemplateURL='https://s3.amazonaws.com/your-bucket/your-template'
)

Of course lots of additional parameters are supported as well.

There is one big caveat: The code above will create a stack, but will not track if the stack creation succeeds. While you can get that information via the describe_stacks call, you can't rely on having a finished stack within that instance of the AWS Lambda function, as the maximum runtime of the AWS Lambda function is 15 minutes, but the CloudFormation stack creation might take longer than that.

If you don't care if the stack creation succeeded you should be good, otherwise I suggest you write the stack id, returned by the create_stack call, to a persistent storage (e.g. DynamoDB) and have a separate scheduled AWS Lambda function which checks the status of the CloudFormation stacks stored in DynamoDB and handles the possible stack creation outcomes.

like image 158
Dunedan Avatar answered Sep 28 '22 11:09

Dunedan