You can execute custom code after your AWS CDK deployments complete, not just during them.
Let’s see this in action. Imagine you’ve just deployed a new API Gateway and Lambda function. You want to immediately invoke that Lambda function with some test data to verify it’s working correctly, all within the same CDK deployment flow.
Here’s a CDK snippet that accomplishes this:
from aws_cdk import Stack, aws_lambda as lambda_, aws_events as events, aws_events_targets as targets, Duration
from constructs import Construct
class TriggerExampleStack(Stack):
def __init__(self, scope: Construct, construct_id: str) -> None:
super().__init__(scope, construct_id)
# Define the Lambda function we want to trigger
my_lambda = lambda_.Function(
self, "MyTestLambda",
runtime=lambda_.Runtime.PYTHON_3_9,
handler="index.handler",
code=lambda_.Code.from_inline("""
import json
def handler(event, context):
print("Lambda triggered with event:", json.dumps(event))
return {
'statusCode': 200,
'body': json.dumps('Hello from triggered Lambda!')
}
""")
)
# Define an EventBridge rule to trigger the Lambda
trigger_rule = events.Rule(
self, "PostDeploymentTrigger",
schedule=events.Schedule.rate(Duration.minutes(0)), # Trigger immediately
targets=[targets.LambdaTarget(my_lambda)]
)
# Pass some event data to the Lambda
trigger_rule.add_event_pattern(
detail={
"message": ["CDK deployment finished"]
}
)
When you deploy this stack using cdk deploy, the MyTestLambda function is created, and immediately after the CloudFormation stack reaches the CREATE_COMPLETE state, the PostDeploymentTrigger EventBridge rule fires. Because the rule is configured to trigger with a rate(0 minutes) and has an event pattern that matches a hypothetical "CDK deployment finished" message (in a real-world scenario, you’d often use a custom event or a more sophisticated integration for this), it invokes MyTestLambda. The event dictionary passed to the Lambda will contain {"message": "CDK deployment finished"}.
This pattern solves the problem of needing to perform post-deployment validation or setup tasks that are dependent on the newly provisioned resources. Instead of manually running scripts or triggering Lambdas separately, you can integrate these actions directly into your CDK deployment lifecycle. The core mechanism is AWS EventBridge (formerly CloudWatch Events). You create a rule that listens for specific events (or a schedule) and define targets, which can be Lambda functions, SQS queues, Step Functions, etc. For immediate post-deployment execution, you can set the schedule to rate(0 minutes) or use specific event patterns that CloudFormation emits upon stack completion.
The key to making this happen after deployment is the events.Rule’s schedule parameter. Setting it to events.Schedule.rate(Duration.minutes(0)) ensures the rule is evaluated and triggered as soon as possible after the stack is created. The targets list specifies what gets invoked. Here, targets.LambdaTarget(my_lambda) points directly to our newly created Lambda function. The add_event_pattern is a way to filter when the rule fires. While rate(0 minutes) triggers it immediately, the event pattern can be used to make it more robust, for instance, if you were triggering based on a specific CloudFormation custom resource completion event.
What most people miss is that the schedule and event_pattern work in tandem. A rate(0 minutes) rule will trigger immediately. However, if you also specify an event_pattern, the target will only be invoked if the event that triggered the rule also matches the pattern. This allows for very fine-grained control. For instance, you could have a rule that triggers on any CloudFormation stack update completion (events.EventPattern(source=["aws.cloudformation"], detail_type=["CloudFormation Stack Status Change"], detail={"status": ["CREATE_COMPLETE", "UPDATE_COMPLETE"]})) but then use an event_pattern within that rule to only invoke your Lambda if the stack name matches a specific pattern or if a particular resource was updated.
This pattern opens the door to automated smoke tests, resource registration, or dynamic configuration updates immediately following any CDK deployment.
The next concept you’ll likely explore is how to pass dynamic outputs from your CDK stack into the event payload for these post-deployment triggers.