Skip to content

feat: add drift detection to cdk as cdk drift #442

New issue

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

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

Already on GitHub? # to your account

Draft
wants to merge 35 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 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
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
1 change: 1 addition & 0 deletions .projenrc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,7 @@ const cloudFormationDiff = configureProject(
deps: [
'@aws-cdk/aws-service-spec',
'@aws-cdk/service-spec-types',
'@aws-sdk/client-cloudformation',
Copy link
Contributor

Choose a reason for hiding this comment

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

If this is now a runtime dep, than it cannot be a peer dep anymore.

'chalk@^4',
'diff',
'fast-deep-equal',
Expand Down
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 DriftableLambdaStack 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 DriftableLambdaStack(app, `${stackPrefix}-driftable-lambda`);
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-lambda', {});

// Assert that, right after deploying, there is no drift (because we just deployed it)
const drift = await fixture.cdk(['drift', '--fail', fixture.fullStackName('driftable-lambda')], { 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-lambda'),
}),
);
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-lambda')], { 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,80 @@
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 --quiet outputs when failing else nothing',
withDefaultFixture(async (fixture) => {
await fixture.cdkDeploy('driftable-lambda', {});

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

expect(drift).not.toMatch(/Stack.*driftable-lambda/); // cant just .toContain because of formatting
expect(drift).not.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-lambda'),
}),
);
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', '--quiet', fixture.fullStackName('driftable-lambda')], { verbose: false });

// Even with --quiet, we should still see an output
expect(driftAfterModification).toMatch(/Stack.*driftable-lambda/);
expect(driftAfterModification).toContain('1 resource has drifted');
}),
);

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-lambda', {});

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

expect(drift).toMatch(/Stack.*driftable-lambda/); // 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-lambda'),
}),
);
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-lambda')], { verbose: false });

const expectedMatches = [
/Stack.*driftable-lambda/,
/[-].*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);
}
}
4 changes: 4 additions & 0 deletions packages/@aws-cdk/cloudformation-diff/.projen/deps.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/@aws-cdk/cloudformation-diff/.projen/tasks.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading