Skip to content

Commit

Permalink
fix(assertions): nested stacks inside non-root stages don't resolve t… (
Browse files Browse the repository at this point in the history
#25006)

…emplates

Templates are placed inside a path described by their closest assembly. Using this assembly lets nested stack templates resolve, regardless of their stage depth. Previously, they would fail to resolve if they were in a stage other than the app.

Closes #24004.
----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
  • Loading branch information
Styerp authored Apr 18, 2023
1 parent 8ca4c09 commit 2d4a60d
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
6 changes: 3 additions & 3 deletions packages/aws-cdk-lib/assertions/lib/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,12 +296,12 @@ export interface TemplateParsingOptions {
}

function toTemplate(stack: Stack): any {
const root = stack.node.root;
if (!Stage.isStage(root)) {
const stage = Stage.of(stack);
if (!Stage.isStage(stage)) {
throw new Error('unexpected: all stacks must be part of a Stage or an App');
}

const assembly = root.synth();
const assembly = stage.synth();
if (stack.nestedStackParent) {
// if this is a nested stack (it has a parent), then just read the template as a string
return JSON.parse(fs.readFileSync(path.join(assembly.directory, stack.templateFile)).toString('utf-8'));
Expand Down
37 changes: 36 additions & 1 deletion packages/aws-cdk-lib/assertions/test/template.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,16 @@
import { App, CfnCondition, CfnMapping, CfnOutput, CfnParameter, CfnResource, Fn, LegacyStackSynthesizer, NestedStack, Stack } from '../../core';
import {
App,
CfnCondition,
CfnMapping,
CfnOutput,
CfnParameter,
CfnResource,
Fn,
LegacyStackSynthesizer,
NestedStack,
Stack,
Stage
} from '../../core';
import { Construct } from 'constructs';
import { Capture, Match, Template } from '../lib';

Expand Down Expand Up @@ -1353,6 +1365,29 @@ describe('Template', () => {
});
}).not.toThrow(/dependency cycle/);
});

test('nested stack inside a Stage in an App', () => {
const app = new App();
const stage = new Stage(app, 'Stage');
const stack = new Stack(stage);
const nested = new NestedStack(stack, 'MyNestedStack');
new CfnResource(nested, 'Bar', {
type: 'Bar::Baz',
properties: {
Qux: 'Foo',
},
});
const template = Template.fromStack(nested);

expect(template.toJSON()).toEqual({
Resources: {
Bar: {
Type: 'Bar::Baz',
Properties: { Qux: 'Foo' },
},
},
});
});
});

function expectToThrow(fn: () => void, msgs: (RegExp | string)[]): void {
Expand Down

0 comments on commit 2d4a60d

Please sign in to comment.