amazon-web-servicesaws-lambdaaws-cdk

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?


Solution

  • You should be able to do this with a CustomResource similar to below:

    const lambdaTrigger = new cr.AwsCustomResource(this, 'MyFunctionTrigger', {
      policy: cr.AwsCustomResourcePolicy.fromStatements([
        new iam.PolicyStatement({
          actions: ['lambda:InvokeFunction'],
          effect: iam.Effect.ALLOW,
          resources: [myFunction.functionArn],
        }),
      ]),
      timeout: Duration.minutes(2),
      onCreate: {
        service: 'Lambda',
        action: 'invoke',
        parameters: {
          FunctionName: myFunction.functionName,
          InvocationType: 'Event',
        },
        physicalResourceId: cr.PhysicalResourceId.of(Date.now().toString()),
      },
      onUpdate: {
        service: 'Lambda',
        action: 'invoke',
        parameters: {
          FunctionName: myFunction.functionName,
          InvocationType: 'Event'
        },
        physicalResourceId: cr.PhysicalResourceId.of(Date.now().toString())
      }
    });
    

    By setting the physicalResourceId to the current time on deploy it should trigger it to execute each deployment.