如何通过CloudFormation运行/测试Lambda函数?部署后实现栈创建自动执行
Great question! Let's break this down into two clear parts: how to run/test your Lambda function after deploying it via CloudFormation, and how to auto-execute the Lambda once your stack finishes creating.
How to Run/Test Your Deployed Lambda via CloudFormation
CloudFormation is built for infrastructure provisioning, not direct function execution—but there are straightforward ways to test your Lambda after deployment:
Option 1: Use CloudFormation Outputs + AWS CLI
This is the simplest approach for manual testing:
- First, add your Lambda's ARN as an output in your CloudFormation template so you can easily retrieve it post-deployment:
Outputs: MyLambdaARN: Description: ARN of the deployed Lambda function Value: !GetAtt MyLambdaFunction.Arn - Once your stack is deployed, fetch the ARN and invoke the Lambda via CLI:
# Get the Lambda ARN from CloudFormation outputs LAMBDA_ARN=$(aws cloudformation describe-stacks --stack-name YourStackName --query "Stacks[0].Outputs[?OutputKey=='MyLambdaARN'].OutputValue" --output text) # Invoke the Lambda (add --payload if your function expects input) aws lambda invoke --function-name $LAMBDA_ARN --payload '{"testKey": "testValue"}' execution-result.json # Check the execution result cat execution-result.json
Option 2: Add a Custom Resource for Automated Testing
If you want to run a test as part of the stack deployment process, use a CloudFormation Custom Resource. This will trigger your Lambda during stack creation to validate it works:
- Update your Lambda to handle CloudFormation custom resource requests (it needs to send a success/failure response back to CloudFormation). Here's a simplified Python example:
import json import requests def lambda_handler(event, context): # Your test logic here print("Running Lambda test...") # Send success response to CloudFormation response = { "Status": "SUCCESS", "Reason": "Test executed successfully", "PhysicalResourceId": context.log_stream_name, "StackId": event["StackId"], "RequestId": event["RequestId"], "LogicalResourceId": event["LogicalResourceId"] } requests.put(event["ResponseURL"], data=json.dumps(response)) return "Test completed" - Add the custom resource to your template:
Resources: # Your existing Lambda function MyLambdaFunction: Type: AWS::Lambda::Function Properties: Runtime: python3.11 Handler: index.lambda_handler Code: S3Bucket: your-code-bucket S3Key: lambda-code.zip Role: !GetAtt LambdaExecutionRole.Arn # Custom resource to trigger Lambda test LambdaTestTrigger: Type: Custom::LambdaTest Properties: ServiceToken: !GetAtt MyLambdaFunction.Arn TestInput: '{"test": "sample-data"}'
How to Auto-Execute Lambda After CloudFormation Stack Creation
There are two reliable methods to tie Lambda execution to your stack's creation completion:
Method 1: Use a CloudFormation Custom Resource (Recommended)
This method binds Lambda execution directly to your stack's lifecycle—if the Lambda fails, your stack will roll back, which is great for critical post-deployment tasks.
- Ensure your Lambda can handle CloudFormation custom resource requests (use the same response logic from the testing example above, but replace the test code with your actual post-deployment logic).
- Add the custom resource to your template, with a
DependsOnclause to wait for all critical resources to be created first:Resources: # Your post-deployment Lambda function PostDeployLambda: Type: AWS::Lambda::Function Properties: Runtime: python3.11 Handler: index.lambda_handler Code: S3Bucket: your-code-bucket S3Key: post-deploy-code.zip Role: !GetAtt LambdaExecutionRole.Arn # Trigger Lambda when stack is ready PostDeployTrigger: Type: Custom::PostDeployTrigger DependsOn: [YourDatabase, YourS3Bucket] # List all resources to wait for Properties: ServiceToken: !GetAtt PostDeployLambda.Arn DeploymentConfig: "production-settings"
Method 2: Use EventBridge (CloudWatch Events)
If you don't want Lambda failures to affect your stack state, use EventBridge to listen for the CREATE_COMPLETE stack event and trigger Lambda:
- Add the EventBridge rule and Lambda invoke permission to your template:
This will trigger your Lambda every time the stack finishes creating successfully. AddResources: # Your post-deployment Lambda PostDeployLambda: Type: AWS::Lambda::Function Properties: Runtime: python3.11 Handler: index.lambda_handler Code: S3Bucket: your-code-bucket S3Key: post-deploy-code.zip Role: !GetAtt LambdaExecutionRole.Arn # EventBridge rule to detect stack creation completion StackCompleteRule: Type: AWS::Events::Rule Properties: Description: Trigger Lambda on stack creation complete EventPattern: source: ["aws.cloudformation"] detail-type: ["CloudFormation Stack Status Change"] detail: stack-name: [!Ref AWS::StackName] status-details: status: ["CREATE_COMPLETE"] Targets: - Arn: !GetAtt PostDeployLambda.Arn Id: "LambdaTarget" # Allow EventBridge to invoke the Lambda LambdaInvokePermission: Type: AWS::Lambda::Permission Properties: FunctionName: !GetAtt PostDeployLambda.Arn Action: "lambda:InvokeFunction" Principal: "events.amazonaws.com" SourceArn: !GetAtt StackCompleteRule.Arn"UPDATE_COMPLETE"to thestatusarray if you want it to run on updates too.
内容的提问来源于stack exchange,提问作者praveen Exclusive

