Skip to content

Commit

Permalink
AspectPriority
Browse files Browse the repository at this point in the history
  • Loading branch information
watany-dev committed Dec 26, 2024
1 parent f2df86d commit dec21e2
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
18 changes: 12 additions & 6 deletions packages/aws-cdk-lib/core/lib/removal-policies.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { IConstruct } from 'constructs';
import { Aspects, IAspect } from './aspect';
import { Aspects, IAspect, AspectPriority } from './aspect';
import { CfnResource } from './cfn-resource';
import { RemovalPolicy } from './removal-policy';

Expand Down Expand Up @@ -28,11 +28,16 @@ export interface RemovalPolicyProps {
* @default false - do not overwrite user-specified policies
*/
readonly overwrite?: boolean;

/**
* The priority to use when applying this aspect.
* If multiple aspects apply conflicting settings, the one with the higher priority wins.
*
* @default - AspectPriority.MUTATING
*/
readonly priority?: number;
}

/**
* The RemovalPolicyAspect handles applying a removal policy to resources
*/
class RemovalPolicyAspect implements IAspect {
constructor(
private readonly policy: RemovalPolicy,
Expand All @@ -46,7 +51,6 @@ class RemovalPolicyAspect implements IAspect {
if (!patterns || patterns.length === 0) {
return false;
}

return patterns.includes(resourceType);
}

Expand Down Expand Up @@ -103,7 +107,9 @@ export class RemovalPolicies {
* @param props Configuration options
*/
public apply(policy: RemovalPolicy, props: RemovalPolicyProps = {}) {
Aspects.of(this.scope).add(new RemovalPolicyAspect(policy, props));
Aspects.of(this.scope).add(new RemovalPolicyAspect(policy, props), {
priority: props.priority ?? AspectPriority.MUTATING,
});
}

/**
Expand Down
14 changes: 14 additions & 0 deletions packages/aws-cdk-lib/core/test/removal-policies.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,4 +220,18 @@ describe('removal-policys', () => {
expect(bucket.cfnOptions.deletionPolicy).toBe('Retain');
expect(table.cfnOptions.deletionPolicy).toBe('RetainExceptOnCreate');
});

test('higher priority removal policy overrides lower priority removal policy', () => {
// GIVEN
const stack = new Stack();
const resource = new TestResource(stack, 'PriorityResource');

// WHEN
RemovalPolicies.of(stack).retainOnUpdateOrDelete({ priority: 250 });
RemovalPolicies.of(stack).destroy({ priority: 10 });

// THEN
synthesize(stack);
expect(resource.cfnOptions.deletionPolicy).toBe('Delete');
});
});

0 comments on commit dec21e2

Please sign in to comment.