I tried creating a set of lambdas using cloudformation. I want the lambdas to get triggered once they are created. I saw at various blogs to create a trigger to s3
or sns
but none seems to be a option to trigger lambda
once it has been created. Any options?
7 Answers
Yes, it is possible. Here are a few options:
Manually create an SNS Topic. Add an
AWS::SNS::Subscription
to your stack with the lambda function as theEndpoint
and the SNS topic as theTopicArn
. On stack creation/update, configure Stack Event Notifications to be sent to this SNS topic.- (See Setting AWS CloudFormation Stack Options for documentation on how to do this when using the AWS Console to create your stack, or use the equivalent option like
--notification-arns
if creating/updating your stack using the AWS CLI or other AWS SDK.)
- (See Setting AWS CloudFormation Stack Options for documentation on how to do this when using the AWS Console to create your stack, or use the equivalent option like
Add a Custom Resource referencing a Lambda function to be called on creation.
- If you need the Lambda function to be called after some specific Resource is created, add a
DependsOn
attribute on the Custom Resource referencing the Resource you want to make sure is created first before the function is called. - In order for the Custom Resource to create successfully (and not cause a failure/rollback in your stack), you will need to adapt your Lambda function to support the CloudFormation request/response format (see Custom Resource Reference).
- This option will call the Lambda function while the stack status is still
CREATE_IN_PROGRESS
, because the Custom Resource is part of the stack itself. - The Lambda function will also be called again when the stack (and associated Custom Resource) is deleted. This will need to be handled by your Lambda function correctly, or your stack could get stuck in the
DELETE_FAILED
state.
- If you need the Lambda function to be called after some specific Resource is created, add a
Add the Lambda function reference to a Stack Output, then write a simple script that performs the stack creation and then manually invokes the Lambda function afterwards.
-
See this to create SNS Topic via SAM docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/….– user3002273Aug 8, 2017 at 15:32
-
1
-
Interesting reference (using serverless framework) for (2): github.com/serverless/serverless/issues/4483– vincentDec 6, 2017 at 5:34
-
Custom Resource
cannot be used to invoke lambda 'after' stack creation has been completed (CREATE_COMPLETE). The lambda is invoked when the stack is 'about to be' created/updated/deleted. Mar 28, 2018 at 10:44 -
1@Abhilashk correct, because the Custom Resource is part of the stack in that case. I've updated Option 2 in the answer to make that more clear.– wjordanMar 28, 2018 at 19:14
by yl.
The following just works great !
It invokes a lambda as a part of deployment:
LambdaFunction2:
Type: AWS::Lambda::Function
Properties:
FunctionName: caller
Code:
ZipFile: |
import boto3, json
import cfnresponse
def handler(event, context):
print('EVENT:[{}]'.format(event))
lambda_client = boto3.client('lambda')
test_event = '{"name":"test1"}'
lambda_client.invoke(
FunctionName='target1',
InvocationType='Event',
Payload=test_event,
)
responseValue = 120
responseData = {}
responseData['Data'] = responseValue
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
Handler: index.handler
Role:
arn:aws:iam::11111111111:role/mylambda-role
Runtime: python3.7
Timeout: 60
Primerinvoke:
Type: AWS::CloudFormation::CustomResource
DependsOn: LambdaFunction2
Version: "1.0"
Properties:
ServiceToken: !GetAtt LambdaFunction2.Arn
-
why do you have the handler attribute if you defined the funcion in the code attribute? Dec 8, 2021 at 20:37
-
For who looking the similar workaround.
CloudWatch is able to capture API calls of CloudFormation, which is "CreateStack", "UpdateStack" and "DeleteStack", stack states like "Create_complete" or "Complete_Rollback" are uncapturable, which means such state changes not be able to trigger lambda.
The workaround is SNS, stacks are able to send notifications to SNS (In advance settings when you creating stack) and SNS can choose to trigger lambda, however, you can't choose for specific states. So, lambda function takes the job to find out what state in "Message" content of an event. Everyone, just coding.
I know this is a bit old- but a solution could also be too use CommandRunner as a resource type in your template.
https://aws.amazon.com/blogs/mt/running-bash-commands-in-aws-cloudformation-templates/.
You can run virtually any shell command. Add a DependsOn attribute to your CommandRunner type and run a shell script:
aws lambda invoke --function-name my-function --invocation-type RequestRespone --payload '{ "name": "Bob" }'
Improving on Kyr's answer, because it lacks two important things:
- how to pass paramaters to the Lambda you invoke
- how to treat UPDATE and DELETE on your Stack (his solution would cause CloudFormation to crash on delete)
Here is the revised and improved code:
LambdaInvoker:
DependsOn: ## important, add stuff here you need to existe BEFORE the lambda is called
Type: AWS::Lambda::Function
Properties:
FunctionName: YourLambdaName
Description: 'Lambda invoke wrapper for Custom CFN actions'
Code:
ZipFile: !Sub |
import boto3, json
import cfnresponse
def handler(event, context):
print('EVENT:')
print(event)
if event['RequestType'] == "Create":
lambda_client = boto3.client('lambda')
cfn_event = {
"param1" : "${Param1}",
"param2" : "${Param2}"
}
lambda_client.invoke(
FunctionName='scm-custom-cfn-actions',
InvocationType='Event',
Payload=json.dumps(cfn_event)
)
responseValue = 120
responseData = {}
responseData['Data'] = responseValue
cfnresponse.send(event, context, cfnresponse.SUCCESS,
responseData, 'scm-cfn-customresource-id')
Handler: index.handler
Role: YourLambdaRoleARN
Runtime: python3.7
Timeout: 5
You have the option to notify to a SNS topic, and you may build a lambda that listens to the topic, so the workflow would be: Cloudformation launch -> SNS Topic -> Lambda.
-
Can I notify my lambda through SNS on creation from cloudformation. I essentially want my lambda to run the moment my cloudformation status changes to CREATE_COMPLETE.– ZZzzZZzzDec 28, 2016 at 15:51
The following template should invoke the lambda :
"InvokeLambda" : {
"Type": "Custom::InvokeLambda",
"Version" : "1.0",
"Properties" : {
"ServiceToken": {
"Fn::GetAtt": ["InitFunction","Arn"]
}
}
},