Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I configure Amazon CDK to trigger a Lambda function after deployment?

I have deployed a Lambda function using Amazon CDK. I would like to invoke this Lambda function automatically every time it is deployed. Is it possible to achieve this using the Amazon CDK construct?

like image 282
Ken Yip Avatar asked Jul 18 '26 16:07

Ken Yip


2 Answers

I've played around with both the triggers.Trigger solution and the customResources.AwsCustomResource solution, but ultimately, while both of these solutions work, they have some minor drawbacks.

The former's drawback is that it doesn't take in an existing lambda.Function, and the latter's drawback is that the Lambda function itself needs to be written as a custom resource event handler, and what's more, we end up with a nonempty CDK diff every time.

I've come up with this solution, which uses an events.Rule rule to trigger myFunction once the CloudFormation stack deployment is complete, and with which I am quite happy:

import * as cdk from "aws-cdk-lib/core";
import * as events from "aws-cdk-lib/aws-events";
import * as eventsTargets from "aws-cdk-lib/aws-events-targets";

new events.Rule(this, "DeploymentHook", {
  eventPattern: {
    detailType: ["CloudFormation Stack Status Change"],
    source: ["aws.cloudformation"],
    detail: {
      "stack-id": [cdk.Stack.of(this).stackId],
      "status-details": {
        status: ["CREATE_COMPLETE", "UPDATE_COMPLETE"],
      },
    },
  },
  targets: [new eventsTargets.LambdaFunction(myFunction)],
});
like image 106
Milosz Avatar answered Jul 21 '26 08:07

Milosz


The canonical way to do this is using CDK triggers, but as @ipbearden correctly points out in the comments, the functionality to run a trigger on every deploy has not been added yet. You can use a hack to always recreate the Trigger on every deploy:

import * as triggers from 'aws-cdk-lib/triggers';

const func: lambda.Function;

new triggers.Trigger(this, 'MyTrigger-' + Date.now().toString(), {
  handler: func,
});

You can even have it execute after (or before) the deployment of a specific construct.

like image 24
gshpychka Avatar answered Jul 21 '26 07:07

gshpychka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!