Using AWS CDK Aspect

Posted on May 18, 2022 • 2 min read

You may have used CDK extensively to provision AWS resources. Did you know CDK also provides other powerful operations to your Constructs? Aspect is one of them.

Aspect is ideal if you want to apply a apply an operation to all constructs in a given scope. This is inspired by Aspect Oriented Programming, where you have a piece of logic that have to be applied at many places.

There are many usage of aspect in CDK. One example is too set the Rentention Policy of all resources in a stack. Example:

import { CfnResource, IAspect, RemovalPolicy, App, Aspects, Stack } from "aws-cdk-lib";
import { IConstruct } from "constructs";

// This aspect set renmoval policy of all resources in a node to DESTROY
export class RemovalPolicyDestroyAspect implements IAspect {
    visit(node: IConstruct): void {
        if (CfnResource.isCfnResource(node)) {
            node.applyRemovalPolicy(RemovalPolicy.DESTROY);
        }
    }
}

const app = new App();
new Stack(app, "stack");
Aspects.of(app).add(new RemovalPolicyDestroyAspect());

The potential is limitless! Another use cases of Aspect is to ensure that versioning is enabled for S3 Buckets

export class RemovalPolicyDestroyAspect implements IAspect {
  visit(node: IConstruct): void {
    if (node instanceof CfnBucket) {
      node.versioningConfiguration = {
        status: "Enabled",
      }
    }
  }
}

Note: CDK Aspect is always executed last before CloudFormation template is synthesized. So it will override any property that you set in the construct.

Conclusion

CDK Aspect allows you to apply a set of operations to all constructs in CDK app. This makes developing CDK app much easier.

Infrastructure team can write Aspect to ensure that the construct follows AWS best practices. In fact, cdk-nag uses aspect extensively to ensure that your AWS CDK app is fully compliant.