CDK Blueprint Property Injection
As of v2.196.0 the AWS CDK now supports property injection. These property injectors provide a way to set default properties for constructs. As of release all L2 constructs (CDK provided) support the PROPERTY_INJECTION_ID
. This allows you to write your own property injectors for a construct. For L3 constructs the maintainers will need to implement this before you can use it.
Here is a simple property injector for S3 buckets that defaults some common settings like blockPublicAccess
.
import { InjectionContext, IPropertyInjector } from "aws-cdk-lib";
import {
BucketProps,
Bucket,
BlockPublicAccess,
BucketEncryption,
} from "aws-cdk-lib/aws-s3";
export class BucketPropsInjector implements IPropertyInjector {
readonly constructUniqueId: string;
constructor() {
this.constructUniqueId = Bucket.PROPERTY_INJECTION_ID;
}
inject(originalProps: BucketProps, context: InjectionContext): BucketProps {
return {
blockPublicAccess: BlockPublicAccess.BLOCK_ALL,
enforceSSL: true,
encryption: BucketEncryption.S3_MANAGED, // this is the default anyway but being explicit here
eventBridgeEnabled: true,
...originalProps,
};
}
}
You can then apply this either at the stack level or the app level:
import { BucketPropsInjector } from "./stacks/property-injectors/bucket-injector";
const app = new App({
propertyInjectors: [new BucketPropsInjector()],
});
const stack = new Stack(app, "test", {
propertyInjectors: [new BucketPropsInjector()],
});
Why would I use this?
This seems really useful for teams wanting to standardize defaults across the board. Many companies have default standards for security reasons for things like buckets, queues, tables, etc. You can now make it easy to comply without constant boilerplate and settings (added bonus that when you spin up a new one and forget you won’t have to fix it later).
Example
In the world of GenAI no one probably cares about these but as always I’ve put together a sample for reference. The tests have three versions tested: no injector, injector in the app, app injector but bucket has props passed in.