This is the AWS CDK v1 Developer Guide. The older CDK v1 entered maintenance on June 1, 2022 and will now only receive critical bug fixes and security patches. New features will be developed for CDK v2 exclusively. Support for CDK v1 will end entirely on June 1, 2023. Migrate to CDK v2 to have access to the latest features and fixes.
Aspects are a way to apply an operation to all constructs in a given scope. The aspect could modify the constructs, such as by adding tags, or it could verify something about the state of the constructs, such as ensuring that all buckets are encrypted.
To apply an aspect to a construct and all constructs in the same scope, call Aspects
.of(
with a
new aspect, as shown in the following example.SCOPE
).add()
Aspects.of(myConstruct).add(new SomeAspect(...));
The AWS CDK uses aspects to tag resources, but the framework can also be used for other purposes. For example, you can use it to validate or change the AWS CloudFormation resources that are defined for you by higher-level constructs.
Aspects in detail
Aspects employ the visitor
pattern
interface IAspect {
visit(node: IConstruct): void;}
When you call Aspects.of(
, the
construct adds the aspect to an internal list of aspects. You can obtain the list with
SCOPE
).add(...)Aspects.of(
.SCOPE
)
During the prepare phase, the AWS CDK calls the
visit
method of the object for the construct and each of its children in
top-down order.
The visit
method is free to change anything in the construct. In
strongly-typed languages, cast the received construct to a more specific type before accessing
construct-specific properties or methods.
Aspects don't propagate across Stage
construct boundaries, because
Stages
are self-contained and immutable after definition. Apply aspects on the
Stage
construct itself (or lower) if you want them to visit constructs inside
the Stage
.
Example
The following example validates that all buckets created in the stack have versioning enabled. The aspect adds an error annotation to the constructs that fail the validation, which results in the synth operation failing and prevents deploying the resulting cloud assembly.
class BucketVersioningChecker implements IAspect {
public visit(node: IConstruct): void {
// See that we're dealing with a CfnBucket
if (node instanceof s3.CfnBucket) {
// Check for versioning property, exclude the case where the property
// can be a token (IResolvable).
if (!node.versioningConfiguration
|| (!Tokenization.isResolvable(node.versioningConfiguration)
&& node.versioningConfiguration.status !== 'Enabled') {
Annotations.of(node).addError('Bucket versioning is not enabled');
}
}
}
}
// Later, apply to the stack
Aspects.of(stack).add(new BucketVersioningChecker());