-
Notifications
You must be signed in to change notification settings - Fork 39
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
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
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
385b970
Move things around and into toolkit lib
8b00bc3
CloudFormation client no longer peer dep
30980ba
De-flag-ify the command
3558e27
Fix formatting
95764ae
Merge with main
d839dcc
FIXED
0c53647
Update README.md
253e1fc
Merge branch 'main' into drift
Leo10Gama dd274fb
Update docstring
a757d37
Cleanup commented code
8c371f8
Several reverts
0f45e98
Merge branch 'main' into drift
Leo10Gama 2a378e1
Merge branch 'drift' of https://github.com/Leo10Gama/aws-cdk-cli into…
620db41
Move drift integ tests to folder
9cb4a4f
Fix import issues with moving tests
c7ce345
Refactor
1a3ff68
Cleanup messges
4df6f78
Fixnaming converntions
f40b58e
Revise tests to use the TestIoHelper
cfd7034
I think that fixed the licensing??
ea8b1b4
Revert some package schenanigans
20d2432
Licensing fixed this time I think
4ad42e0
Merge remote-tracking branch 'origin/main' into pr/Leo10Gama/442
rix0rrr d71d113
Fix IoHelper import
ba01d82
Fix license
5bb17fd
Merge branch 'main' into drift
Leo10Gama 953b6d0
Implement requested changes
df5fc27
Merge branch 'main' into drift
Leo10Gama 6a6b591
Fix testing errors
d8192aa
Minor change
7d06468
Merge branch 'main' into drift
mrgrain 2fd132c
fixes
mrgrain 05ee4c1
test fixes
mrgrain b51c75c
fixup integ test
mrgrain 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
77 changes: 77 additions & 0 deletions
77
...sts/cli-integ-tests/drift/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', {}); | ||
|
||
// 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); | ||
} | ||
} |
19 changes: 19 additions & 0 deletions
19
...ests/cli-integ-tests/drift/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/drift/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', {}); | ||
|
||
// 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); | ||
} | ||
} |
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
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; | ||
} |
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
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
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.
Uh oh!
There was an error while loading. Please reload this page.