-
Notifications
You must be signed in to change notification settings - Fork 25
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
Leo10Gama
wants to merge
35
commits into
aws:main
Choose a base branch
from
Leo10Gama:drift
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
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
7c4e1fc
Fix output for no drifts
3caf9c9
Add drift detection to cdk diff
87cf1f3
Fix output for no drifts
004fcab
Merge
cf553de
Merge branch 'drift' of https://github.com/Leo10Gama/aws-cdk-cli into…
3c0b3a4
Not sure how all that got there lmao oops
75e9b90
Add test for multiple resources
d9e7540
Move drift logic to helper function
df9d1aa
Duplicate into toolkit-lib
ce99b6f
Remove ResourceDriftStatus enum
953bea1
Minor tweaks
32dabb9
Update timeout mechanism
496227a
Move driftResults to be within TemplateInfo
e49a035
Change message when driftResults is undefined
b02598b
Merge branch 'main' into drift
e8b1853
Merge hell has been traversed
d31a642
Move drift to its own command
f4768f1
Merge branch 'main' into drift
2fbaa2c
Move cfn-api methods to api/drift
43291d9
Make numResourcesDrifted optional to simplify output
a8cee87
Among other things, added integration tests
7eb13d8
Merge branch 'main' into drift
Leo10Gama 3f41ed2
Include verbose optioning
cf0768a
Intermediate merge commit
f6d2a1c
I
5bf35d2
Merged from main
aa4f0d7
Merge and add test coverage
64b44dd
Merge branch 'main' into drift
Leo10Gama 6908202
Merge branch 'main' into drift
Leo10Gama dd46a89
Remove stack name from error message
ebe3a29
Merge branch 'drift' of https://github.com/Leo10Gama/aws-cdk-cli into…
1e8c8d9
Fix bug where verboe message appeared in output always
c10140c
Update README.md
ed6e1a7
Add intermediary message while drift detection running
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
77 changes: 77 additions & 0 deletions
77
...teg/tests/cli-integ-tests/cdk-cdk-drift---fail-throws-when-drift-is-detected.integtest.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |
80 changes: 80 additions & 0 deletions
80
...ests/cli-integ-tests/cdk-cdk-drift---quiet-outputs-when-failing-else-nothing.integtest.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |
19 changes: 19 additions & 0 deletions
19
...nteg/tests/cli-integ-tests/cdk-cdk-drift---verbose-shows-unchecked-resources.integtest.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
}), | ||
); |
96 changes: 96 additions & 0 deletions
96
packages/@aws-cdk-testing/cli-integ/tests/cli-integ-tests/cdk-cdk-drift.integtest.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.