Sub topic 14
Sharing values across stacks
This chapter assumes you can define a stack with S3 and Lambda resources, and that you know tokens are placeholders resolved at deploy time. Here you will see how one stack uses a resource defined in another, what CloudFormation does underneath, and the failures this causes.
Why split into stacks at all
A stack is the unit CloudFormation deploys, updates and rolls back. Splitting an app into several stacks is useful in these cases:
- Stateful resources (buckets, tables) change rarely, while application code changes often. Separate stacks keep a bad code deploy away from your data.
- A single stack has a limit of 500 resources.
- Different stacks can have different owners, lifecycles or target environments.
Once resources live in different stacks, a Lambda function in one stack may need the name or ARN of a bucket in another. CloudFormation cannot see across stacks on its own, so the CDK arranges the link for you.
Passing constructs as props
The idiomatic approach is to expose the resource as a public property and pass it into the next stack through its props.
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as lambda from 'aws-cdk-lib/aws-lambda';
export class DataStack extends cdk.Stack {
public readonly bucket: s3.Bucket;
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
this.bucket = new s3.Bucket(this, 'UploadsBucket', {
versioned: true,
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
}
}
export interface ComputeStackProps extends cdk.StackProps {
readonly bucket: s3.IBucket;
}
export class ComputeStack extends cdk.Stack {
constructor(scope: Construct, id: string, props: ComputeStackProps) {
super(scope, id, props);
const fn = new lambda.Function(this, 'Processor', {
runtime: lambda.Runtime.NODEJS_20_X,
handler: 'index.handler',
code: lambda.Code.fromInline('exports.handler = async () => ({});'),
environment: { BUCKET_NAME: props.bucket.bucketName },
});
props.bucket.grantRead(fn);
}
}
const app = new cdk.App();
const env = {
account: process.env.CDK_DEFAULT_ACCOUNT,
region: process.env.CDK_DEFAULT_REGION,
};
const data = new DataStack(app, 'DataStack', { env });
new ComputeStack(app, 'ComputeStack', { env, bucket: data.bucket });The prop type is s3.IBucket, the interface, not the concrete Bucket class. That lets the consumer accept a bucket created in this app or one imported from elsewhere.
The same pattern in Python uses a keyword argument:
from aws_cdk import App, Environment, RemovalPolicy, Stack
from aws_cdk import aws_lambda as _lambda
from aws_cdk import aws_s3 as s3
from constructs import Construct
import os
class DataStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
self.bucket = s3.Bucket(
self, "UploadsBucket", versioned=True, removal_policy=RemovalPolicy.RETAIN
)
class ComputeStack(Stack):
def __init__(self, scope: Construct, construct_id: str, *, bucket: s3.IBucket, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
fn = _lambda.Function(
self,
"Processor",
runtime=_lambda.Runtime.PYTHON_3_12,
handler="index.handler",
code=_lambda.Code.from_inline("def handler(event, context):\n return {}"),
environment={"BUCKET_NAME": bucket.bucket_name},
)
bucket.grant_read(fn)
app = App()
env = Environment(
account=os.environ.get("CDK_DEFAULT_ACCOUNT"),
region=os.environ.get("CDK_DEFAULT_REGION"),
)
data = DataStack(app, "DataStack", env=env)
ComputeStack(app, "ComputeStack", env=env, bucket=data.bucket)
app.synth()What the CDK generates
bucket.bucketName is a token. When the CDK sees that a token from DataStack is used inside ComputeStack, it does three things during synthesis:
- Adds an
Outputsentry with anExportname to theDataStacktemplate. The name is generated and starts with the stack name. - Replaces the token in
ComputeStackwithFn::ImportValuepointing at that export name. - Records that
ComputeStackdepends onDataStack, so CloudFormation deploys the data stack first.
You can confirm this by running cdk synth DataStack and looking at the Outputs section of the template.
The deadly embrace
Exports are locked while any stack imports them. This causes two problems.
- You cannot delete or change an exported value while a consumer still uses it. CloudFormation fails the update with a message that the export is in use.
- If you stop using a cross-stack value in the consumer and deploy the producer first, the CDK removes the export from the producer, and that deploy fails.
To remove a reference safely, keep the export alive while you change the consumer. Call exportValue in the producer:
// Inside DataStack's constructor: keeps the export in the template
this.exportValue(this.bucket.bucketName);Deploy with this line, deploy the consumer without the reference, then remove the line and deploy again.
Cyclic dependencies
Dependencies must flow one way. A cycle appears when each stack needs something from the other. A common cause is an event notification: if the bucket lives in DataStack and sends events to a Lambda in ComputeStack, the bucket now depends on the function. Combined with the function's dependency on the bucket, the CDK reports a cyclic reference at synthesis.
Fixes, in order of preference:
- Put the two linked resources in the same stack.
- Create the event wiring in the stack that owns the consumer, so the dependency points one way.
- Pass a name or ARN as a plain string (see the next section) instead of a construct reference.
Alternatives to direct references
| Approach | Link between stacks | Use when |
|---|---|---|
| Construct as prop | CloudFormation export and import | Both stacks are in the same app, account and region |
| `Bucket.fromBucketName` and similar `from*` methods | None, only a string | The resource is outside the app or you need to avoid a dependency |
| SSM parameter | Parameter Store value read at deploy time | Stacks are deployed independently or by different teams |
| `crossRegionReferences: true` | Custom resources that copy values | Stacks are in different regions of the same app |
An imported bucket gives you an IBucket that supports grants and other methods, but the CDK cannot create or modify it:
const shared = s3.Bucket.fromBucketName(this, 'Shared', 'my-existing-bucket');
shared.grantRead(fn);For cross-region use, set the flag on both stacks and give each an explicit env, since the CDK needs to know both regions at synthesis:
const data = new DataStack(app, 'DataStack', {
env: { account: '123456789012', region: 'us-east-1' },
crossRegionReferences: true,
});
new ComputeStack(app, 'ComputeStack', {
env: { account: '123456789012', region: 'eu-west-1' },
crossRegionReferences: true,
bucket: data.bucket,
});Organizing stacks
- Separate stateful stacks (buckets, tables, queues) from stateless ones (functions, APIs).
- Let the stateful stack be the producer, so the data stack never depends on the code stack.
- Keep cross-stack references few and obvious. A stack that imports a dozen values is probably in the wrong place.
- Deploy a specific stack with
cdk deploy ComputeStack. The CDK also deploys any stacks it depends on if they are not already up to date.
Exercise
DataStack exports a bucket name that ComputeStack imports. You remove the reference from ComputeStack's code and deploy only DataStack first. What happens, and how do you avoid it?
Show answer
DataStack's template no longer has the export, but ComputeStack still imports it, so CloudFormation rejects the update because the export is in use. To avoid it, add this.exportValue(bucket.bucketName) to DataStack so the export stays, deploy ComputeStack without the reference, then remove the exportValue line and deploy DataStack again.
Exercise
A bucket in DataStack should invoke a Lambda function in ComputeStack on object creation, and ComputeStack already receives the bucket as a prop. Synthesis reports a cyclic reference. Why, and what is the simplest fix?
Show answer
The event notification makes the bucket depend on the function, while the function depends on the bucket, so the stacks depend on each other. The simplest fix is to define the bucket and the function in the same stack. Alternatively, import the bucket in ComputeStack by name and add the notification there.