Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(CLI): diff --template crashes #29896

Merged
merged 7 commits into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/@aws-cdk/cloudformation-diff/lib/diff-template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ export function fullDiff(
isImport?: boolean,
): types.TemplateDiff {

if (!currentTemplate || !newTemplate) {
throw new Error('trying to diff a template that is not defined');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does that error even mean? How do I fix this?

}

normalize(currentTemplate);
normalize(newTemplate);
const theDiff = diffTemplate(currentTemplate, newTemplate);
Expand Down
13 changes: 13 additions & 0 deletions packages/@aws-cdk/cloudformation-diff/test/diff-template.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,19 @@ test('metadata changes are rendered in the diff', () => {
expect(differences.resources.differenceCount).toBe(1);
});

test('diff complains if it receives an undefined template', async () => {
// GIVEN
const currentTemplate: any = undefined;

// WHEN
const newTemplate = {
Resources: {},
};

// THEN
expect(() => fullDiff(currentTemplate, newTemplate)).toThrow(/trying to diff a template that is not defined/);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From this code I can get why there is this check. But how would an actual user end up with this? How can they fix it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A user would never end up with this. I added it because diff is design to work on arbitrary json objects, but it achieves this by typing things as any, which allows undefined. undefined breaks it though, so I figured we could be a bit more defensive with that. It's not doing anything useful though, it's just moving the crash earlier, so I can remove this

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason this change got through is it looked innocuous and it didn't break any tests, because we had just never tested fixed-template diffs before

});

describe('changeset', () => {
test('changeset overrides spec replacements', () => {
// GIVEN
Expand Down
35 changes: 2 additions & 33 deletions packages/aws-cdk/lib/cdk-toolkit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,41 +136,10 @@ export class CdkToolkit {
throw new Error(`There is no file at ${options.templatePath}`);
}

let changeSet = undefined;

if (options.changeSet) {
let stackExists = false;
try {
stackExists = await this.props.deployments.stackExists({
stack: stacks.firstStack,
deployName: stacks.firstStack.stackName,
tryLookupRole: true,
});
} catch (e: any) {
debug(e.message);
stream.write('Checking if the stack exists before creating the changeset has failed, will base the diff on template differences (run again with -v to see the reason)\n');
stackExists = false;
}

if (stackExists) {
changeSet = await createDiffChangeSet({
stack: stacks.firstStack,
uuid: uuid.v4(),
deployments: this.props.deployments,
willExecute: false,
sdkProvider: this.props.sdkProvider,
parameters: Object.assign({}, parameterMap['*'], parameterMap[stacks.firstStack.stackName]),
stream,
});
} else {
debug(`the stack '${stacks.firstStack.stackName}' has not been deployed to CloudFormation or describeStacks call failed, skipping changeset creation.`);
}
}

const template = deserializeStructure(await fs.readFile(options.templatePath, { encoding: 'UTF-8' }));
diffs = options.securityOnly
? numberFromBool(printSecurityDiff(template, stacks.firstStack, RequireApproval.Broadening, changeSet))
: printStackDiff(template, stacks.firstStack.template, strict, contextLines, quiet, changeSet, false, stream);
? numberFromBool(printSecurityDiff(template, stacks.firstStack, RequireApproval.Broadening, undefined))
: printStackDiff(template, stacks.firstStack, strict, contextLines, quiet, undefined, false, stream);
} else {
// Compare N stacks against deployed templates
for (const stack of stacks.stackArtifacts) {
Expand Down
69 changes: 69 additions & 0 deletions packages/aws-cdk/test/diff.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,75 @@ let cloudExecutable: MockCloudExecutable;
let cloudFormation: jest.Mocked<Deployments>;
let toolkit: CdkToolkit;

describe('fixed template', () => {
const templatePath = 'oldTemplate.json';
beforeEach(() => {
const oldTemplate = {
Resources: {
SomeResource: {
Type: 'AWS::SomeService::SomeResource',
Properties: {
Something: 'old-value',
},
},
},
};

cloudExecutable = new MockCloudExecutable({
stacks: [{
stackName: 'A',
template: {
Resources: {
SomeResource: {
Type: 'AWS::SomeService::SomeResource',
Properties: {
Something: 'new-value',
},
},
},
},
}],
});

toolkit = new CdkToolkit({
cloudExecutable,
deployments: cloudFormation,
configuration: cloudExecutable.configuration,
sdkProvider: cloudExecutable.sdkProvider,
});

fs.writeFileSync(templatePath, JSON.stringify(oldTemplate));
});

afterEach(() => fs.rmSync(templatePath));

test('fixed template with valid templates', async () => {
// GIVEN
const buffer = new StringWritable();

// WHEN
const exitCode = await toolkit.diff({
stackNames: ['A'],
stream: buffer,
changeSet: undefined,
templatePath,
});

// THEN
const plainTextOutput = buffer.data.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, '');
expect(exitCode).toBe(0);
expect(plainTextOutput.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, '')).toContain(`Resources
[~] AWS::SomeService::SomeResource SomeResource
└─ [~] Something
├─ [-] old-value
└─ [+] new-value


✨ Number of stacks with differences: 1
`);
});
});

describe('imports', () => {
beforeEach(() => {
const outputToJson = {
Expand Down
Loading