Applicable when
- Using some construct or resource that creates a circular relation between different resources - e.g. bind an Event Source that triggers a lambda for each object created into an S3 bucket and you want to create an environment variable to keep the bucket website URL on the lambda
- On the example above, the lambda depends on the S3 bucket to know the address for the bucket; also, the S3 bucket depends on the lambda as a listener for its insertions. If these two elements reside on different stacks, CDK will complain that there is a circular reference among them.
Non-applicable when
- You already have the two dependent elements associated with the same stack
Implementation
The majority of built-in class constructors from CDK accept a parameter where you can specify the stack you want to assign it.
Most of them also provide the stack property that allows you to pick up the parent, making it easy to put the circular-dependent elements into the same stack, resolving the issue in a way that is not emphasized enough on the documentation.
CDK Definition
import * as lambda from '@aws-cdk/aws-lambda';
import * as s3 from '@aws-cdk/aws-s3';
import * as lambdaEventSources from '@aws-cdk/aws-lambda-event-sources';
import * as cdk from '@aws-cdk/core';
export class MySampleConstruct extends cdk.Construct {
constructor(scope: cdk.Construct, lambda: lambda.Function) {
super(scope, 'MySampleConstruct');
const bucket = new s3.Bucket(lambda.stack, 'MyBucket', { /* ...definitions */ });
const eventSource = new lambdaEventSources.S3EventSource(bucket, {
events: [s3.EventType.OBJECT_CREATED],
filters: [{prefix: 'my-fancy-prefix/'}],
});
lambda.addEventSource(eventSource);
lambda.addEnvironment('S3_BUCKET_URL', bucket.bucketWebsiteUrl);
}
}
Lambda Definition
export class handler() {
console.log(`The target bucket website is ${process.env.S3_BUCKET_URL}`);
}
Comments
0 comments
Please sign in to leave a comment.