Skip to content

feat: diff shows moved resources #708

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

Merged
merged 19 commits into from
Jul 15, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
8 changes: 8 additions & 0 deletions packages/@aws-cdk/cloudformation-diff/lib/diff/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,12 @@ export interface Resource {
[key: string]: any;
}

export interface Move {
readonly direction: 'from' | 'to';
readonly stackName: string;
readonly resourceLogicalId: string;
}

/**
* Change to a single resource between two CloudFormation templates
*
Expand All @@ -568,6 +574,8 @@ export class ResourceDifference implements IDifference<Resource> {
*/
public isImport?: boolean;

public move?: Move;

/** Property-level changes on the resource */
private readonly propertyDiffs: { [key: string]: PropertyDifference<any> };

Expand Down
17 changes: 14 additions & 3 deletions packages/@aws-cdk/cloudformation-diff/lib/format.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { format } from 'util';
import * as chalk from 'chalk';
import type { DifferenceCollection, TemplateDiff } from './diff/types';
import type { DifferenceCollection, Move, TemplateDiff } from './diff/types';
import { deepEqual } from './diff/util';
import type { Difference, ResourceDifference } from './diff-template';
import { isPropertyDifference, ResourceImpact } from './diff-template';
Expand Down Expand Up @@ -166,8 +166,15 @@ export class Formatter {

const resourceType = diff.isRemoval ? diff.oldResourceType : diff.newResourceType;

// eslint-disable-next-line @stylistic/max-len
this.print(`${this.formatResourcePrefix(diff)} ${this.formatValue(resourceType, chalk.cyan)} ${this.formatLogicalId(logicalId)} ${this.formatImpact(diff.changeImpact)}`.trimEnd());
const message = [
this.formatResourcePrefix(diff),
this.formatValue(resourceType, chalk.cyan),
this.formatLogicalId(logicalId),
this.formatImpact(diff.changeImpact),
this.formatMove(diff.move),
].filter(Boolean).join(' ');

this.print(message);

if (diff.isUpdate) {
const differenceCount = diff.differenceCount;
Expand Down Expand Up @@ -239,6 +246,10 @@ export class Formatter {
}
}

private formatMove(move?: Move): string {
return !move ? '' : chalk.yellow('(OR', chalk.italic(chalk.bold('move')), `${move.direction} ${move.stackName}.${move.resourceLogicalId} via refactoring)`);
}

/**
* Renders a tree of differences under a particular name.
* @param name - the name of the root of the tree.
Expand Down
8 changes: 8 additions & 0 deletions packages/@aws-cdk/toolkit-lib/lib/actions/diff/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,12 @@ export interface DiffOptions {
* @default 3
*/
readonly contextLines?: number;

/**
* Whether to include resource moves in the diff. These are the same moves that are detected
* by the `refactor` command.
*
* @default false
*/
readonly includeMoves?: boolean;
}
10 changes: 10 additions & 0 deletions packages/@aws-cdk/toolkit-lib/lib/actions/diff/private/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type { ResourcesToImport } from '../../../api/resource-import';
import { removeNonImportResources, ResourceMigrator } from '../../../api/resource-import';
import { ToolkitError } from '../../../toolkit/toolkit-error';
import { deserializeStructure, formatErrorMessage } from '../../../util';
import { mappingsByEnvironment } from '../../refactor/index';

export function prepareDiff(
ioHelper: IoHelper,
Expand Down Expand Up @@ -67,6 +68,10 @@ async function cfnDiff(
const templateInfos = [];
const methodOptions = (options.method?.options ?? {}) as ChangeSetDiffOptions;

const allMappings = options.includeMoves
? await mappingsByEnvironment(stacks.stackArtifacts, sdkProvider, true)
: [];

// Compare N stacks against deployed templates
for (const stack of stacks.stackArtifacts) {
const templateWithNestedStacks = await deployments.readCurrentTemplateWithNestedStacks(
Expand All @@ -93,12 +98,17 @@ async function cfnDiff(
methodOptions.importExistingResources,
) : undefined;

const mappings = allMappings.find(m =>
m.environment.region === stack.environment.region && m.environment.account === stack.environment.account,
)?.mappings ?? {};

templateInfos.push({
oldTemplate: currentTemplate,
newTemplate: stack,
isImport: !!resourcesToImport,
nestedStacks,
changeSet,
mappings,
});
}

Expand Down
29 changes: 28 additions & 1 deletion packages/@aws-cdk/toolkit-lib/lib/actions/refactor/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type * as cxapi from '@aws-cdk/cx-api';
import type { StackSelector } from '../../api';
import type { SdkProvider } from '../../api/aws-auth/sdk-provider';
import type { ExcludeList } from '../../api/refactoring';
import { InMemoryExcludeList, NeverExclude } from '../../api/refactoring';
import { groupStacks, InMemoryExcludeList, NeverExclude, RefactoringContext } from '../../api/refactoring';
import { ToolkitError } from '../../toolkit/toolkit-error';

type MappingType = 'auto' | 'explicit';
Expand Down Expand Up @@ -142,3 +144,28 @@ export function parseMappingGroups(s: string) {
}
}
}

export interface EnvironmentSpecificMappings {
readonly environment: cxapi.Environment;
readonly mappings: Record<string, string>;
}

export async function mappingsByEnvironment(
stackArtifacts: cxapi.CloudFormationStackArtifact[],
sdkProvider: SdkProvider,
ignoreModifications?: boolean,
): Promise<EnvironmentSpecificMappings[]> {
const groups = await groupStacks(sdkProvider, stackArtifacts, []);
return groups.map((group) => {
const context = new RefactoringContext({
...group,
ignoreModifications,
});
return {
environment: context.environment,
mappings: Object.fromEntries(
Copy link
Contributor

Choose a reason for hiding this comment

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

Rather than splatting down the object to a string here, aren't we better off maintaining the object and rendering it later when it comes time to present the diff?

context.mappings.map((m) => [m.source.toLocationString(), m.destination.toLocationString()]),
),
};
});
}
42 changes: 39 additions & 3 deletions packages/@aws-cdk/toolkit-lib/lib/api/diff/diff-formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
formatSecurityChanges,
fullDiff,
mangleLikeCloudFormation,
type ResourceDifference,
type TemplateDiff,
} from '@aws-cdk/cloudformation-diff';
import type * as cxapi from '@aws-cdk/cx-api';
Expand Down Expand Up @@ -122,6 +123,14 @@ export interface TemplateInfo {
readonly nestedStacks?: {
[nestedStackLogicalId: string]: NestedStackTemplates;
};

/**
* Mappings of old locations to new locations. If these are provided,
* for all resources that were moved, their corresponding addition
* and removal lines will be augmented with the location they were
* moved fom and to, respectively.
*/
readonly mappings?: Record<string, string>;
}

/**
Expand All @@ -134,6 +143,7 @@ export class DiffFormatter {
private readonly changeSet?: any;
private readonly nestedStacks: { [nestedStackLogicalId: string]: NestedStackTemplates } | undefined;
private readonly isImport: boolean;
private readonly mappings: Record<string, string>;

/**
* Stores the TemplateDiffs that get calculated in this DiffFormatter,
Expand All @@ -148,6 +158,7 @@ export class DiffFormatter {
this.changeSet = props.templateInfo.changeSet;
this.nestedStacks = props.templateInfo.nestedStacks;
this.isImport = props.templateInfo.isImport ?? false;
this.mappings = props.templateInfo.mappings ?? {};
}

public get diffs() {
Expand All @@ -159,16 +170,38 @@ export class DiffFormatter {
* If it creates the diff, it stores the result in a map for
* easier retrieval later.
*/
private diff(stackName?: string, oldTemplate?: any) {
private diff(stackName?: string, oldTemplate?: any, mappings: Record<string, string> = {}) {
const realStackName = stackName ?? this.stackName;

if (!this._diffs[realStackName]) {
this._diffs[realStackName] = fullDiff(
const templateDiff = fullDiff(
oldTemplate ?? this.oldTemplate,
this.newTemplate.template,
this.changeSet,
this.isImport,
);

const setMove = (change: ResourceDifference, direction: 'from' | 'to', location?: string)=> {
if (location != null) {
const [sourceStackName, sourceLogicalId] = location.split('.');
change.move = {
direction,
stackName: sourceStackName,
resourceLogicalId: sourceLogicalId,
};
}
};

templateDiff.resources.forEachDifference((id, change) => {
const location = `${realStackName}.${id}`;
if (change.isAddition && Object.values(mappings).includes(location)) {
setMove(change, 'from', Object.keys(mappings).find(k => mappings[k] === location));
} else if (change.isRemoval && Object.keys(mappings).includes(location)) {
setMove(change, 'to', mappings[location]);
}
});

this._diffs[realStackName] = templateDiff;
}
return this._diffs[realStackName];
}
Expand Down Expand Up @@ -199,6 +232,7 @@ export class DiffFormatter {
this.stackName,
this.nestedStacks,
options,
this.mappings,
);
}

Expand All @@ -207,8 +241,9 @@ export class DiffFormatter {
stackName: string,
nestedStackTemplates: { [nestedStackLogicalId: string]: NestedStackTemplates } | undefined,
options: ReusableStackDiffOptions,
mappings: Record<string, string> = {},
) {
let diff = this.diff(stackName, oldTemplate);
let diff = this.diff(stackName, oldTemplate, mappings);

// The stack diff is formatted via `Formatter`, which takes in a stream
// and sends its output directly to that stream. To facilitate use of the
Expand Down Expand Up @@ -279,6 +314,7 @@ export class DiffFormatter {
nestedStack.physicalName ?? nestedStackLogicalId,
nestedStack.nestedStackTemplates,
options,
this.mappings,
);
numStacksWithChanges += nextDiff.numStacksWithChanges;
formattedDiff += nextDiff.formattedDiff;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,19 @@ export class ResourceLocation {
}

public toPath(): string {
const stack = this.stack;
const resource = stack.template.Resources?.[this.logicalResourceId];
const resource = this.stack.template.Resources?.[this.logicalResourceId];
const result = resource?.Metadata?.['aws:cdk:path'];

if (result != null) {
return result;
}

// If the path is not available, we can use stack name and logical ID
return `${stack.stackName}.${this.logicalResourceId}`;
return this.toLocationString();
}

public toLocationString() {
return `${this.stack.stackName}.${this.logicalResourceId}`;
}

public getType(): string {
Expand Down
25 changes: 17 additions & 8 deletions packages/@aws-cdk/toolkit-lib/lib/api/refactoring/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ import { equalSets } from '../../util/sets';
*/
type ResourceMove = [ResourceLocation[], ResourceLocation[]];

export interface RefactorManagerOptions {
export interface RefactoringContextOptions {
environment: Environment;
localStacks: CloudFormationStack[];
deployedStacks: CloudFormationStack[];
overrides?: ResourceMapping[];
ignoreModifications?: boolean;
}

/**
Expand All @@ -28,9 +29,9 @@ export class RefactoringContext {
private readonly ambiguousMoves: ResourceMove[] = [];
public readonly environment: Environment;

constructor(props: RefactorManagerOptions) {
constructor(props: RefactoringContextOptions) {
this.environment = props.environment;
const moves = resourceMoves(props.deployedStacks, props.localStacks, 'direct');
const moves = resourceMoves(props.deployedStacks, props.localStacks, 'direct', props.ignoreModifications);
const additionalOverrides = structuralOverrides(props.deployedStacks, props.localStacks);
const overrides = (props.overrides ?? []).concat(additionalOverrides);
const [nonAmbiguousMoves, ambiguousMoves] = partitionByAmbiguity(overrides, moves);
Expand Down Expand Up @@ -70,20 +71,28 @@ export class RefactoringContext {
*
*/
function structuralOverrides(deployedStacks: CloudFormationStack[], localStacks: CloudFormationStack[]): ResourceMapping[] {
const moves = resourceMoves(deployedStacks, localStacks, 'opposite');
const moves = resourceMoves(deployedStacks, localStacks, 'opposite', true);
const [nonAmbiguousMoves] = partitionByAmbiguity([], moves);
return resourceMappings(nonAmbiguousMoves);
}

function resourceMoves(before: CloudFormationStack[], after: CloudFormationStack[], direction: GraphDirection): ResourceMove[] {
function resourceMoves(
before: CloudFormationStack[],
after: CloudFormationStack[],
direction: GraphDirection = 'direct',
ignoreModifications: boolean = false): ResourceMove[] {
const digestsBefore = resourceDigests(before, direction);
const digestsAfter = resourceDigests(after, direction);

const stackNames = (stacks: CloudFormationStack[]) => stacks.map((s) => s.stackName).sort().join(', ');
if (!isomorphic(digestsBefore, digestsAfter)) {
const stackNames = (stacks: CloudFormationStack[]) =>
stacks
.map((s) => s.stackName)
.sort()
.join(', ');
if (!(ignoreModifications || isomorphic(digestsBefore, digestsAfter))) {
const message = [
'A refactor operation cannot add, remove or update resources. Only resource moves and renames are allowed. ',
'Run \'cdk diff\' to compare the local templates to the deployed stacks.\n',
"Run 'cdk diff' to compare the local templates to the deployed stacks.\n",
`Deployed stacks: ${stackNames(before)}`,
`Local stacks: ${stackNames(after)}`,
];
Expand Down
1 change: 1 addition & 0 deletions packages/@aws-cdk/toolkit-lib/lib/api/refactoring/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import type { MappingGroup } from '../../actions';
import { ToolkitError } from '../../toolkit/toolkit-error';

export * from './exclude';
export * from './context';

interface StackGroup {
environment: cxapi.Environment;
Expand Down
Loading
Loading