DEV Community

3

Automate Post-Deployment Tasks with `cdkTrigger` in AWS CDK

Deploying infrastructure with AWS CDK is powerful — but sometimes, you want something more than just resources in place. Maybe you want to:

  • Seed a database after deployment
  • Populate an S3 bucket with default data
  • Kick off a workflow
  • Or simply validate that everything deployed successfully

That's where the cdk-triggers module comes in. In this post, we'll walk through how to use cdk.triggers.Trigger to automatically invoke a Lambda function after a successful CDK deployment.


🔧 What is cdk.triggers.Trigger?

The Trigger construct is part of the aws-cdk-lib.triggers module. It allows you to run a Lambda automatically after your stack is deployed — great for bootstrapping and post-deploy configuration tasks.


🧪 Example: Run a Lambda After Resources Are Created

Let’s say you’re deploying:

  • An S3 bucket
  • A DynamoDB table
  • A Lambda that seeds a database

You want the Lambda to run after all the resources are successfully created.

Step 1: Import Required Modules

import * as cdk from "aws-cdk-lib";
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as s3 from "aws-cdk-lib/aws-s3";
import * as dynamodb from "aws-cdk-lib/aws-dynamodb";
import * as triggers from "aws-cdk-lib/triggers";
import { Construct } from "constructs";
Enter fullscreen mode Exit fullscreen mode

Step 2: Define the Stack

export class MyStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // S3 bucket
    const bucket = new s3.Bucket(this, "MyBucket");

    // DynamoDB table
    const table = new dynamodb.Table(this, "MyTable", {
      partitionKey: { name: "id", type: dynamodb.AttributeType.STRING },
    });

    // Lambda function to run post-deploy
    const seedFunction = new lambda.Function(this, "SeedFunction", {
      runtime: lambda.Runtime.NODEJS_18_X,
      handler: "index.handler",
      code: lambda.Code.fromAsset("lambda/seed"),
      timeout: cdk.Duration.minutes(5),
      environment: {
        BUCKET_NAME: bucket.bucketName,
        TABLE_NAME: table.tableName,
      },
    });

    bucket.grantReadWrite(seedFunction);
    table.grantReadWriteData(seedFunction);

    // Create the trigger
    const cdkTrigger = new triggers.Trigger(this, "SeedTrigger", {
      handler: seedFunction,
      timeout: cdk.Duration.minutes(10),
      invocationType: triggers.InvocationType.EVENT, // async invocation
    });

    // Define dependencies – only run trigger after these resources are created
    cdkTrigger.executeAfter(bucket);
    cdkTrigger.executeAfter(table);
  }
}
Enter fullscreen mode Exit fullscreen mode

🔁 How It Works

During deployment, CDK will:

  1. Deploy your stack’s resources (bucket, table, Lambda).
  2. Automatically invoke the seedFunction via the trigger.
  3. Ensure it runs only once (unless you opt to re-run it).

🛠 Notes & Best Practices

  • The Trigger construct deploys a custom resource under the hood.
  • The invocationType can be:

    • EVENT: Asynchronous (default and recommended for non-critical background jobs)
    • REQUEST_RESPONSE: Wait for result (useful for critical tasks, but can cause stack rollback on failure)
  • You can use cdkTrigger.executeAfter(...) to control execution order and guarantee your resources are ready.

  • To re-run the trigger every deploy, set cdkTrigger.trigger.runOnUpdate = true.


🧹 Optional: Clean Up After Execution

By default, the Lambda and the trigger stay in place. If you want to clean up the Lambda after running:

cdkTrigger.applyRemovalPolicy(cdk.RemovalPolicy.DESTROY);
Enter fullscreen mode Exit fullscreen mode

Or consider separating your post-deployment logic into a one-time stack.


✅ Summary

cdk.triggers.Trigger is a great way to kick off post-deployment automation in a clean, repeatable way.

Use it to:

  • Seed databases
  • Initialize state
  • Validate configs
  • Or automate any once-per-deploy logic

No need for separate scripts or manual steps — just CDK.


📁 Example Directory Structure

my-app/
├── bin/
│   └── my-app.ts
├── lib/
│   └── my-stack.ts
├── lambda/
│   └── seed/
│       └── index.ts
Enter fullscreen mode Exit fullscreen mode

🧪 Want to Try It?

Make sure you have the triggers module installed:

npm install aws-cdk-lib constructs
Enter fullscreen mode Exit fullscreen mode

That’s it! Happy automating with CDK! ⚙️

Build gen AI apps that run anywhere with MongoDB Atlas

Build gen AI apps that run anywhere with MongoDB Atlas

MongoDB Atlas bundles vector search and a flexible document model so developers can build, scale, and run gen AI apps without juggling multiple databases. From LLM to semantic search, Atlas streamlines AI architecture. Start free today.

Start Free

Top comments (0)

Best Practices for Running  Container WordPress on AWS (ECS, EFS, RDS, ELB) using CDK cover image

Best Practices for Running Container WordPress on AWS (ECS, EFS, RDS, ELB) using CDK

This post discusses the process of migrating a growing WordPress eShop business to AWS using AWS CDK for an easily scalable, high availability architecture. The detailed structure encompasses several pillars: Compute, Storage, Database, Cache, CDN, DNS, Security, and Backup.

Read full post

👋 Kindness is contagious

Explore this practical breakdown on DEV’s open platform, where developers from every background come together to push boundaries. No matter your experience, your viewpoint enriches the conversation.

Dropping a simple “thank you” or question in the comments goes a long way in supporting authors—your feedback helps ideas evolve.

At DEV, shared discovery drives progress and builds lasting bonds. If this post resonated, a quick nod of appreciation can make all the difference.

Okay