Package software.amazon.awscdk.mixins.preview


@Stability(Experimental) package software.amazon.awscdk.mixins.preview

CDK Mixins (Preview)

---

cdk-constructs: Experimental

The APIs of higher level constructs in this module are experimental and under active development. They are subject to non-backward compatible changes or removal in any future version. These are not subject to the Semantic Versioning model and breaking changes will be announced in the release notes. This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package.


This package provides two main features:

  1. Mixins - Composable abstractions for adding functionality to constructs
  2. EventBridge Event Patterns - Type-safe event patterns for AWS resources


CDK Mixins

CDK Mixins provide a new, advanced way to add functionality through composable abstractions. Unlike traditional L2 constructs that bundle all features together, Mixins allow you to pick and choose exactly the capabilities you need for constructs.

Key Benefits

  • Universal Compatibility: Apply the same abstractions to L1 constructs, L2 constructs, or custom constructs
  • Composable Design: Mix and match features without being locked into specific implementations
  • Cross-Service Abstractions: Use common patterns like encryption across different AWS services
  • Escape Hatch Freedom: Customize resources in a safe, typed way while keeping the abstractions you want

Basic Usage

Mixins use Mixins.of() as the fundamental API for applying abstractions to constructs:

 // Base form: apply mixins to any construct
 CfnBucket bucket = new CfnBucket(scope, "MyBucket");
 Mixins.of(bucket).apply(new EncryptionAtRest()).apply(new AutoDeleteObjects());
 

Fluent Syntax with .with()

For convenience, you can use the .with() method for a more fluent syntax:

 CfnBucket bucket = new CfnBucket(scope, "MyBucket").with(new EnableVersioning()).with(new AutoDeleteObjects());
 

The .with() method is available after importing @aws-cdk/mixins-preview/with, which augments all constructs with this method. It provides the same functionality as Mixins.of().apply() but with a more chainable API.

Note: The .with() fluent syntax is only available in JavaScript and TypeScript. Other jsii languages (Python, Java, C#, and Go) should use the Mixins.of(...).mustApply() syntax instead. The import requirement is temporary during the preview phase. Once the API is stable, the .with() method will be available by default on all constructs and in all languages.

Creating Custom Mixins

Mixins are simple classes that implement the IMixin interface (usually by extending the abstract Mixin class:

 // Simple mixin that enables versioning
 public class CustomVersioningMixin extends Mixin implements IMixin {
     public boolean supports(Object construct) {
         return construct instanceof CfnBucket;
     }
 
     public Object applyTo(Object bucket) {
         bucket.getVersioningConfiguration() = Map.of(
                 "status", "Enabled");
         return bucket;
     }
 }
 
 // Usage
 CfnBucket bucket = new CfnBucket(scope, "MyBucket");
 Mixins.of(bucket).apply(new CustomVersioningMixin());
 

Construct Selection

Mixins operate on construct trees and can be applied selectively:

 // Apply to all constructs in a scope
 Mixins.of(scope).apply(new EncryptionAtRest());
 
 // Apply to specific resource types
 Mixins.of(scope, ConstructSelector.resourcesOfType(CfnBucket.CFN_RESOURCE_TYPE_NAME)).apply(new EncryptionAtRest());
 
 // Apply to constructs matching a path pattern
 Mixins.of(scope, ConstructSelector.byPath("**/*-prod-*/**")).apply(new ProductionSecurityMixin());
 

Built-in Mixins

Cross-Service Mixins

EncryptionAtRest: Applies encryption to supported AWS resources

 // Works across different resource types
 CfnBucket bucket = new CfnBucket(scope, "Bucket");
 Mixins.of(bucket).apply(new EncryptionAtRest());
 
 CfnLogGroup logGroup = new CfnLogGroup(scope, "LogGroup");
 Mixins.of(logGroup).apply(new EncryptionAtRest());
 

S3-Specific Mixins

AutoDeleteObjects: Configures automatic object deletion for S3 buckets

 CfnBucket bucket = new CfnBucket(scope, "Bucket");
 Mixins.of(bucket).apply(new AutoDeleteObjects());
 

EnableVersioning: Enables versioning on S3 buckets

 CfnBucket bucket = new CfnBucket(scope, "Bucket");
 Mixins.of(bucket).apply(new EnableVersioning());
 

Logs Delivery

Configures vended logs delivery for supported resources to various destinations:

 import software.amazon.awscdk.mixins.preview.services.cloudfront.mixins.*;
 
 // Create CloudFront distribution
 Bucket bucket;
 
 Distribution distribution = Distribution.Builder.create(scope, "Distribution")
         .defaultBehavior(BehaviorOptions.builder()
                 .origin(S3BucketOrigin.withOriginAccessControl(bucket))
                 .build())
         .build();
 
 // Create log destination
 LogGroup logGroup = new LogGroup(scope, "DeliveryLogGroup");
 
 // Configure log delivery using the mixin
 distribution.with(CfnDistributionLogsMixin.CONNECTION_LOGS.toLogGroup(logGroup));
 

L1 Property Mixins

For every CloudFormation resource, CDK Mixins automatically generates type-safe property mixins. These allow you to apply L1 properties with full TypeScript support:

 Bucket bucket = new Bucket(scope, "Bucket").with(CfnBucketPropsMixin.Builder.create()
         .versioningConfiguration(VersioningConfigurationProperty.builder().status("Enabled").build())
         .publicAccessBlockConfiguration(PublicAccessBlockConfigurationProperty.builder()
                 .blockPublicAcls(true)
                 .blockPublicPolicy(true)
                 .build())
         .build());
 

Property mixins support two merge strategies:

 CfnBucket bucket;
 
 
 // MERGE (default): Deep merges properties with existing values
 Mixins.of(bucket).apply(CfnBucketPropsMixin.Builder.create(CfnBucketMixinProps.builder().versioningConfiguration(VersioningConfigurationProperty.builder().status("Enabled").build()).build()).strategy(PropertyMergeStrategy.MERGE).build());
 
 // OVERRIDE: Replaces existing property values
 Mixins.of(bucket).apply(CfnBucketPropsMixin.Builder.create(CfnBucketMixinProps.builder().versioningConfiguration(VersioningConfigurationProperty.builder().status("Enabled").build()).build()).strategy(PropertyMergeStrategy.OVERRIDE).build());
 

Property mixins are available for all AWS services:

 import software.amazon.awscdk.mixins.preview.services.logs.mixins.CfnLogGroupPropsMixin;
 import software.amazon.awscdk.mixins.preview.services.lambda.mixins.CfnFunctionPropsMixin;
 import software.amazon.awscdk.mixins.preview.services.dynamodb.mixins.CfnTablePropsMixin;
 

Error Handling

Mixins provide comprehensive error handling:

 // Graceful handling of unsupported constructs
 Mixins.of(scope).apply(new EncryptionAtRest()); // Skips unsupported constructs
 
 // Strict application that requires all constructs to match
 Mixins.of(scope).mustApply(new EncryptionAtRest());
 


EventBridge Event Patterns

CDK Mixins automatically generates typed EventBridge event patterns for AWS resources. These patterns work with both L1 and L2 constructs, providing a consistent interface for creating EventBridge rules.

Event Patterns Basic Usage

 import software.amazon.awscdk.mixins.preview.services.s3.events.BucketEvents;
 import software.amazon.awscdk.services.events.*;
 import software.amazon.awscdk.services.events.targets.*;
 Function fn;
 
 
 // Works with L2 constructs
 Bucket bucket = new Bucket(scope, "Bucket");
 BucketEvents bucketEvents = BucketEvents.fromBucket(bucket);
 
 Rule.Builder.create(scope, "Rule")
         .eventPattern(bucketEvents.objectCreatedPattern(ObjectCreatedProps.builder()
                 .object(ObjectType.builder().key(List.of("uploads/*")).build())
                 .build()))
         .targets(List.of(new LambdaFunction(fn)))
         .build();
 
 // Also works with L1 constructs
 CfnBucket cfnBucket = new CfnBucket(scope, "CfnBucket");
 BucketEvents cfnBucketEvents = BucketEvents.fromBucket(cfnBucket);
 
 CfnRule.Builder.create(scope, "CfnRule")
         .state("ENABLED")
         .eventPattern(cfnBucketEvents.objectCreatedPattern(ObjectCreatedProps.builder()
                 .object(ObjectType.builder().key(List.of("uploads/*")).build())
                 .build()))
         .targets(List.of(TargetProperty.builder().arn(fn.getFunctionArn()).id("L1").build()))
         .build();
 

Event Pattern Features

Automatic Resource Injection: Resource identifiers are automatically included in patterns

 import software.amazon.awscdk.mixins.preview.services.s3.events.BucketEvents;
 
 Bucket bucket;
 
 BucketEvents bucketEvents = BucketEvents.fromBucket(bucket);
 
 // Bucket name is automatically injected from the bucket reference
 EventPattern pattern = bucketEvents.objectCreatedPattern();
 

Event Metadata Support: Control EventBridge pattern metadata

 import software.amazon.awscdk.mixins.preview.services.s3.events.BucketEvents;
 
 Bucket bucket;
 
 BucketEvents bucketEvents = BucketEvents.fromBucket(bucket);
 
 EventPattern pattern = bucketEvents.objectCreatedPattern(ObjectCreatedProps.builder()
         .eventMetadata(AWSEventMetadataProps.builder()
                 .region(List.of("us-east-1", "us-west-2"))
                 .version(List.of("0"))
                 .build())
         .build());
 

Available Events

Event patterns are generated for EventBridge events available in the AWS Event Schema Registry. Common examples:

S3 Events:

  • objectCreatedPattern() - Object creation events
  • objectDeletedPattern() - Object deletion events
  • objectTagsAddedPattern() - Object tagging events
  • awsAPICallViaCloudTrailPattern() - CloudTrail API calls

Import events from service-specific modules:

 import software.amazon.awscdk.mixins.preview.services.s3.events.BucketEvents;