Skip to content

feat(cli,toolkit-lib): drift detection via cdk drift and toolkit.drift() #442

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 69 commits into from
May 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
69 commits
Select commit Hold shift + click to select a range
0620818
Add drift detection to cdk diff
May 1, 2025
7c4e1fc
Fix output for no drifts
May 1, 2025
3caf9c9
Add drift detection to cdk diff
May 1, 2025
87cf1f3
Fix output for no drifts
May 1, 2025
004fcab
Merge
May 1, 2025
cf553de
Merge branch 'drift' of https://github.com/Leo10Gama/aws-cdk-cli into…
May 1, 2025
3c0b3a4
Not sure how all that got there lmao oops
May 1, 2025
75e9b90
Add test for multiple resources
May 1, 2025
d9e7540
Move drift logic to helper function
May 2, 2025
df9d1aa
Duplicate into toolkit-lib
May 2, 2025
ce99b6f
Remove ResourceDriftStatus enum
May 2, 2025
953bea1
Minor tweaks
May 5, 2025
32dabb9
Update timeout mechanism
May 5, 2025
496227a
Move driftResults to be within TemplateInfo
May 5, 2025
e49a035
Change message when driftResults is undefined
May 5, 2025
b02598b
Merge branch 'main' into drift
May 5, 2025
e8b1853
Merge hell has been traversed
May 5, 2025
d31a642
Move drift to its own command
May 7, 2025
f4768f1
Merge branch 'main' into drift
May 7, 2025
2fbaa2c
Move cfn-api methods to api/drift
May 7, 2025
43291d9
Make numResourcesDrifted optional to simplify output
May 7, 2025
a8cee87
Among other things, added integration tests
May 8, 2025
7eb13d8
Merge branch 'main' into drift
Leo10Gama May 8, 2025
3f41ed2
Include verbose optioning
May 12, 2025
cf0768a
Intermediate merge commit
May 13, 2025
f6d2a1c
I
May 13, 2025
5bf35d2
Merged from main
May 13, 2025
aa4f0d7
Merge and add test coverage
May 14, 2025
64b44dd
Merge branch 'main' into drift
Leo10Gama May 14, 2025
6908202
Merge branch 'main' into drift
Leo10Gama May 15, 2025
dd46a89
Remove stack name from error message
May 15, 2025
ebe3a29
Merge branch 'drift' of https://github.com/Leo10Gama/aws-cdk-cli into…
May 15, 2025
1e8c8d9
Fix bug where verboe message appeared in output always
May 15, 2025
c10140c
Update README.md
May 15, 2025
ed6e1a7
Add intermediary message while drift detection running
May 16, 2025
385b970
Move things around and into toolkit lib
May 21, 2025
8b00bc3
CloudFormation client no longer peer dep
May 21, 2025
30980ba
De-flag-ify the command
May 21, 2025
3558e27
Fix formatting
May 21, 2025
95764ae
Merge with main
May 21, 2025
d839dcc
FIXED
May 22, 2025
0c53647
Update README.md
May 22, 2025
253e1fc
Merge branch 'main' into drift
Leo10Gama May 22, 2025
dd274fb
Update docstring
May 22, 2025
a757d37
Cleanup commented code
May 22, 2025
8c371f8
Several reverts
May 23, 2025
0f45e98
Merge branch 'main' into drift
Leo10Gama May 23, 2025
2a378e1
Merge branch 'drift' of https://github.com/Leo10Gama/aws-cdk-cli into…
May 23, 2025
620db41
Move drift integ tests to folder
May 23, 2025
9cb4a4f
Fix import issues with moving tests
May 23, 2025
c7ce345
Refactor
May 23, 2025
1a3ff68
Cleanup messges
May 23, 2025
4df6f78
Fixnaming converntions
May 23, 2025
f40b58e
Revise tests to use the TestIoHelper
May 24, 2025
cfd7034
I think that fixed the licensing??
May 24, 2025
ea8b1b4
Revert some package schenanigans
May 24, 2025
20d2432
Licensing fixed this time I think
May 24, 2025
4ad42e0
Merge remote-tracking branch 'origin/main' into pr/Leo10Gama/442
rix0rrr May 26, 2025
d71d113
Fix IoHelper import
May 26, 2025
ba01d82
Fix license
May 26, 2025
5bb17fd
Merge branch 'main' into drift
Leo10Gama May 26, 2025
953b6d0
Implement requested changes
May 26, 2025
df5fc27
Merge branch 'main' into drift
Leo10Gama May 26, 2025
6a6b591
Fix testing errors
May 26, 2025
d8192aa
Minor change
May 26, 2025
7d06468
Merge branch 'main' into drift
mrgrain May 27, 2025
2fd132c
fixes
mrgrain May 27, 2025
05ee4c1
test fixes
mrgrain May 27, 2025
b51c75c
fixup integ test
mrgrain May 27, 2025
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
29 changes: 29 additions & 0 deletions packages/@aws-cdk-testing/cli-integ/resources/cdk-apps/app/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,33 @@ class LambdaStack extends cdk.Stack {
}
}

class DriftableStack extends cdk.Stack {
constructor(parent, id, props) {
const synthesizer = parent.node.tryGetContext('legacySynth') === 'true' ?
new LegacyStackSynthesizer({
fileAssetsBucketName: parent.node.tryGetContext('bootstrapBucket'),
})
: new DefaultStackSynthesizer({
fileAssetsBucketName: parent.node.tryGetContext('bootstrapBucket'),
})
super(parent, id, {
...props,
synthesizer: synthesizer,
});

const fn = new lambda.Function(this, 'my-function', {
code: lambda.Code.asset(path.join(__dirname, 'lambda')),
runtime: lambda.Runtime.NODEJS_LATEST,
handler: 'index.handler',
description: 'This is my function!',
timeout: cdk.Duration.seconds(5),
memorySize: 128
});

new cdk.CfnOutput(this, 'FunctionArn', { value: fn.functionArn });
}
}

class IamRolesStack extends cdk.Stack {
constructor(parent, id, props) {
super(parent, id, props);
Expand Down Expand Up @@ -942,6 +969,8 @@ switch (stackSet) {
new BundlingStage(app, `${stackPrefix}-bundling-stage`);

new MetadataStack(app, `${stackPrefix}-metadata`);

new DriftableStack(app, `${stackPrefix}-driftable`);
break;

case 'stage-using-context':
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { DescribeStackResourcesCommand } from '@aws-sdk/client-cloudformation';
import { GetFunctionCommand, UpdateFunctionConfigurationCommand } from '@aws-sdk/client-lambda';
import { integTest, sleep, withDefaultFixture } from '../../../lib';

jest.setTimeout(2 * 60 * 60_000); // Includes the time to acquire locks, worst-case single-threaded runtime

integTest(
'cdk drift --fail throws when drift is detected',
withDefaultFixture(async (fixture) => {
await fixture.cdkDeploy('driftable', {});

// Assert that, right after deploying, there is no drift (because we just deployed it)
const drift = await fixture.cdk(['drift', '--fail', fixture.fullStackName('driftable')], { verbose: false });

expect(drift).toContain('No drift detected');

// Get the Lambda, we want to now make it drift
const response = await fixture.aws.cloudFormation.send(
new DescribeStackResourcesCommand({
StackName: fixture.fullStackName('driftable'),
}),
);
const lambdaResource = response.StackResources?.find(
resource => resource.ResourceType === 'AWS::Lambda::Function',
);
if (!lambdaResource || !lambdaResource.PhysicalResourceId) {
throw new Error('Could not find Lambda function in stack resources');
}
const functionName = lambdaResource.PhysicalResourceId;

// Update the Lambda function, introducing drift
await fixture.aws.lambda.send(
new UpdateFunctionConfigurationCommand({
FunctionName: functionName,
Description: 'I\'m slowly drifting (drifting away)',
}),
);

// Wait for the stack update to complete
await waitForLambdaUpdateComplete(fixture, functionName);

await expect(
fixture.cdk(['drift', '--fail', fixture.fullStackName('driftable')], { verbose: false }),
).rejects.toThrow('exited with error');
}),
);

async function waitForLambdaUpdateComplete(fixture: any, functionName: string): Promise<void> {
const delaySeconds = 5;
const timeout = 30_000; // timeout after 30s
const deadline = Date.now() + timeout;

while (true) {
const response = await fixture.aws.lambda.send(
new GetFunctionCommand({
FunctionName: functionName,
}),
);

const lastUpdateStatus = response.Configuration?.LastUpdateStatus;

if (lastUpdateStatus === 'Successful') {
return; // Update completed successfully
}

if (lastUpdateStatus === 'Failed') {
throw new Error('Lambda function update failed');
}

if (Date.now() > deadline) {
throw new Error(`Timed out after ${timeout / 1000} seconds.`);
}

// Wait before checking again
await sleep(delaySeconds * 1000);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { integTest, withDefaultFixture } from '../../../lib';

jest.setTimeout(2 * 60 * 60_000); // Includes the time to acquire locks, worst-case single-threaded runtime

integTest(
'cdk drift --verbose shows unchecked resources',
withDefaultFixture(async (fixture) => {
await fixture.cdkDeploy('define-vpc', { modEnv: { ENABLE_VPC_TESTING: 'DEFINE' } });

// Assert that there's no drift when we deploy it, but there should be
// unchecked resources, as there are some EC2 connection resources
// (e.g. SubnetRouteTableAssociation) that do not support drift detection
const drift = await fixture.cdk(['drift', '--verbose', fixture.fullStackName('define-vpc')], { modEnv: { ENABLE_VPC_TESTING: 'DEFINE' } });

expect(drift).toMatch(/Stack.*define-vpc/); // cant just .toContain because of formatting
expect(drift).toContain('No drift detected');
expect(drift).toContain('(3 unchecked)'); // 2 SubnetRouteTableAssociations, 1 VPCGatewayAttachment
}),
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { DescribeStackResourcesCommand } from '@aws-sdk/client-cloudformation';
import { GetFunctionCommand, UpdateFunctionConfigurationCommand } from '@aws-sdk/client-lambda';
import { integTest, sleep, withDefaultFixture } from '../../../lib';

jest.setTimeout(2 * 60 * 60_000); // Includes the time to acquire locks, worst-case single-threaded runtime

integTest(
'cdk drift',
withDefaultFixture(async (fixture) => {
await fixture.cdkDeploy('driftable', {});

// Assert that, right after deploying, there is no drift (because we just deployed it)
const drift = await fixture.cdk(['drift', fixture.fullStackName('driftable')], { verbose: false });

expect(drift).toMatch(/Stack.*driftable/); // can't just .toContain because of formatting
expect(drift).toContain('No drift detected');
expect(drift).toContain('✨ Number of resources with drift: 0');
expect(drift).not.toContain('unchecked'); // should not see unchecked resources unless verbose

// Get the Lambda, we want to now make it drift
const response = await fixture.aws.cloudFormation.send(
new DescribeStackResourcesCommand({
StackName: fixture.fullStackName('driftable'),
}),
);
const lambdaResource = response.StackResources?.find(
resource => resource.ResourceType === 'AWS::Lambda::Function',
);
if (!lambdaResource || !lambdaResource.PhysicalResourceId) {
throw new Error('Could not find Lambda function in stack resources');
}
const functionName = lambdaResource.PhysicalResourceId;

// Update the Lambda function, introducing drift
await fixture.aws.lambda.send(
new UpdateFunctionConfigurationCommand({
FunctionName: functionName,
Description: 'I\'m slowly drifting (drifting away)',
}),
);

// Wait for the stack update to complete
await waitForLambdaUpdateComplete(fixture, functionName);

const driftAfterModification = await fixture.cdk(['drift', fixture.fullStackName('driftable')], { verbose: false });

const expectedMatches = [
/Stack.*driftable/,
/[-].*This is my function!/m,
/[+].*I'm slowly drifting \(drifting away\)/m,
];
const expectedSubstrings = [
'1 resource has drifted', // num resources drifted
'✨ Number of resources with drift: 1',
'AWS::Lambda::Function', // the lambda should be marked drifted
'/Description', // the resources that have drifted
];
for (const expectedMatch of expectedMatches) {
expect(driftAfterModification).toMatch(expectedMatch);
}
for (const expectedSubstring of expectedSubstrings) {
expect(driftAfterModification).toContain(expectedSubstring);
}
}),
);

async function waitForLambdaUpdateComplete(fixture: any, functionName: string): Promise<void> {
const delaySeconds = 5;
const timeout = 30_000; // timeout after 30s
const deadline = Date.now() + timeout;

while (true) {
const response = await fixture.aws.lambda.send(
new GetFunctionCommand({
FunctionName: functionName,
}),
);

const lastUpdateStatus = response.Configuration?.LastUpdateStatus;

if (lastUpdateStatus === 'Successful') {
return; // Update completed successfully
}

if (lastUpdateStatus === 'Failed') {
throw new Error('Lambda function update failed');
}

if (Date.now() > deadline) {
throw new Error(`Timed out after ${timeout / 1000} seconds.`);
}

// Wait before checking again
await sleep(delaySeconds * 1000);
}
}
2 changes: 2 additions & 0 deletions packages/@aws-cdk/toolkit-lib/docs/message-registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ Please let us know by [opening an issue](https://github.com/aws/aws-cdk-cli/issu
| `CDK_TOOLKIT_E3900` | Resource import failed | `error` | {@link ErrorPayload} |
| `CDK_TOOLKIT_I4000` | Diff stacks is starting | `trace` | {@link StackSelectionDetails} |
| `CDK_TOOLKIT_I4001` | Output of the diff command | `info` | {@link DiffResult} |
| `CDK_TOOLKIT_I4590` | Results of the drift command | `result` | {@link DriftResultPayload} |
| `CDK_TOOLKIT_I4591` | Missing drift result fort a stack. | `warn` | {@link SingleStack} |
| `CDK_TOOLKIT_I5000` | Provides deployment times | `info` | {@link Duration} |
| `CDK_TOOLKIT_I5001` | Provides total time in deploy action, including synth and rollback | `info` | {@link Duration} |
| `CDK_TOOLKIT_I5002` | Provides time for resource migration | `info` | {@link Duration} |
Expand Down
58 changes: 58 additions & 0 deletions packages/@aws-cdk/toolkit-lib/lib/actions/drift/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import type { StackSelector } from '../../api/cloud-assembly';

export interface DriftOptions {
/**
* Criteria for selecting stacks to check for drift
*/
readonly stacks: StackSelector;
}

/**
* The different types of drift as formatted drift output
*
* A missing type implies no drift of this type.
* If no drift was detected at all, all will be missing.
*/
export interface FormattedDrift {
/**
* Resources that have not changed
*/
readonly unchanged?: string;

/**
* Resources that were not checked for drift
*/
readonly unchecked?: string;

/**
* Resources with drift
*/
readonly modified?: string;

/**
* Resources that have been deleted (drift)
*/
readonly deleted?: string;
}

/**
* Combined drift for selected stacks of the app
*/
export interface DriftResult {
/**
* Number of resources with drift. If undefined, then an error occurred
* and resources were not properly checked for drift.
*/
readonly numResourcesWithDrift: number;

/**
* How many resources were not checked for drift. If undefined, then an
* error occurred and resources were not properly checked for drift.
*/
readonly numResourcesUnchecked: number;

/**
* Complete formatted drift
*/
readonly formattedDrift: FormattedDrift;
}
1 change: 1 addition & 0 deletions packages/@aws-cdk/toolkit-lib/lib/actions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export * from './bootstrap';
export * from './deploy';
export * from './destroy';
export * from './diff';
export * from './drift';
export * from './list';
export * from './refactor';
export * from './rollback';
Expand Down
24 changes: 24 additions & 0 deletions packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,14 @@ import type {
UpdateTerminationProtectionCommandInput,
UpdateTerminationProtectionCommandOutput,
StackSummary,
DescribeStackDriftDetectionStatusCommandInput,
DescribeStackDriftDetectionStatusCommandOutput,
DescribeStackResourceDriftsCommandOutput,
DetectStackDriftCommandInput,
DetectStackDriftCommandOutput,
DetectStackResourceDriftCommandInput,
DetectStackResourceDriftCommandOutput,
DescribeStackResourceDriftsCommandInput,
} from '@aws-sdk/client-cloudformation';
import {
paginateListStacks,
Expand Down Expand Up @@ -120,6 +128,10 @@ import {
StartResourceScanCommand,
UpdateStackCommand,
UpdateTerminationProtectionCommand,
DescribeStackDriftDetectionStatusCommand,
DescribeStackResourceDriftsCommand,
DetectStackDriftCommand,
DetectStackResourceDriftCommand,
} from '@aws-sdk/client-cloudformation';
import type {
FilterLogEventsCommandInput,
Expand Down Expand Up @@ -419,8 +431,12 @@ export interface ICloudFormationClient {
input: DescribeGeneratedTemplateCommandInput,
): Promise<DescribeGeneratedTemplateCommandOutput>;
describeResourceScan(input: DescribeResourceScanCommandInput): Promise<DescribeResourceScanCommandOutput>;
describeStackDriftDetectionStatus(input: DescribeStackDriftDetectionStatusCommandInput): Promise<DescribeStackDriftDetectionStatusCommandOutput>;
describeStacks(input: DescribeStacksCommandInput): Promise<DescribeStacksCommandOutput>;
describeStackResourceDrifts(input: DescribeStackResourceDriftsCommandInput): Promise<DescribeStackResourceDriftsCommandOutput>;
describeStackResources(input: DescribeStackResourcesCommandInput): Promise<DescribeStackResourcesCommandOutput>;
detectStackDrift(input: DetectStackDriftCommandInput): Promise<DetectStackDriftCommandOutput>;
detectStackResourceDrift(input: DetectStackResourceDriftCommandInput): Promise<DetectStackResourceDriftCommandOutput>;
executeChangeSet(input: ExecuteChangeSetCommandInput): Promise<ExecuteChangeSetCommandOutput>;
getGeneratedTemplate(input: GetGeneratedTemplateCommandInput): Promise<GetGeneratedTemplateCommandOutput>;
getTemplate(input: GetTemplateCommandInput): Promise<GetTemplateCommandOutput>;
Expand Down Expand Up @@ -681,13 +697,21 @@ export class SDK {
): Promise<DeleteGeneratedTemplateCommandOutput> => client.send(new DeleteGeneratedTemplateCommand(input)),
deleteStack: (input: DeleteStackCommandInput): Promise<DeleteStackCommandOutput> =>
client.send(new DeleteStackCommand(input)),
detectStackDrift: (input: DetectStackDriftCommandInput): Promise<DetectStackDriftCommandOutput> =>
client.send(new DetectStackDriftCommand(input)),
detectStackResourceDrift: (input: DetectStackResourceDriftCommandInput): Promise<DetectStackResourceDriftCommandOutput> =>
client.send(new DetectStackResourceDriftCommand(input)),
describeChangeSet: (input: DescribeChangeSetCommandInput): Promise<DescribeChangeSetCommandOutput> =>
client.send(new DescribeChangeSetCommand(input)),
describeGeneratedTemplate: (
input: DescribeGeneratedTemplateCommandInput,
): Promise<DescribeGeneratedTemplateCommandOutput> => client.send(new DescribeGeneratedTemplateCommand(input)),
describeResourceScan: (input: DescribeResourceScanCommandInput): Promise<DescribeResourceScanCommandOutput> =>
client.send(new DescribeResourceScanCommand(input)),
describeStackDriftDetectionStatus: (input: DescribeStackDriftDetectionStatusCommandInput):
Promise<DescribeStackDriftDetectionStatusCommandOutput> => client.send(new DescribeStackDriftDetectionStatusCommand(input)),
describeStackResourceDrifts: (input: DescribeStackResourceDriftsCommandInput): Promise<DescribeStackResourceDriftsCommandOutput> =>
client.send(new DescribeStackResourceDriftsCommand(input)),
describeStacks: (input: DescribeStacksCommandInput): Promise<DescribeStacksCommandOutput> =>
client.send(new DescribeStacksCommand(input)),
describeStackResources: (input: DescribeStackResourcesCommandInput): Promise<DescribeStackResourcesCommandOutput> =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ interface DiffFormatterProps {
}

/**
* PRoperties specific to formatting the stack diff
* Properties specific to formatting the stack diff
*/
interface FormatStackDiffOptions {
/**
Expand Down
Loading