Last active
November 9, 2024 19:02
-
-
Save Rud5G/dc68d56ed6f2131f4486c8da9221ba6a to your computer and use it in GitHub Desktop.
addCfnNagSuppression
This file contains 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
import { CfnResource } from 'aws-cdk-lib'; | |
import { IConstruct } from 'constructs'; | |
export interface CfnNagSuppression { | |
readonly id: string; | |
readonly reason: string; | |
} | |
export function addCfnNagSuppression(resource: IConstruct, suppression: CfnNagSuppression): void { | |
const cfnResource = resource.node.defaultChild as CfnResource; | |
if (!cfnResource?.cfnOptions) { | |
throw new Error(`Resource ${cfnResource?.logicalId} has no cfnOptions, unable to add cfn-nag suppression`); | |
} | |
const existingSuppressions: CfnNagSuppression[] = cfnResource.cfnOptions.metadata?.cfn_nag?.rules_to_suppress; | |
if (existingSuppressions) { | |
existingSuppressions.push(suppression); | |
} else { | |
cfnResource.cfnOptions.metadata = { | |
cfn_nag: { | |
rules_to_suppress: [suppression], | |
}, | |
}; | |
} | |
} |
This file contains 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
import { CfnResource, Stack } from 'aws-cdk-lib'; | |
import { Bucket } from 'aws-cdk-lib/aws-s3'; | |
import { addCfnNagSuppression, CfnNagSuppression } from './add-cfn-nag-suppression'; | |
describe('add cfn-nag suppression', function () { | |
it('adds suppression when none present', function () { | |
const stack = new Stack(); | |
const bucket = new Bucket(stack, 'Bucket'); | |
const suppression: CfnNagSuppression = { id: 'my id', reason: 'my reason' }; | |
addCfnNagSuppression(bucket, suppression); | |
expect((bucket.node.defaultChild as CfnResource).cfnOptions.metadata?.cfn_nag?.rules_to_suppress).toStrictEqual( | |
expect.arrayContaining([suppression]), | |
); | |
}); | |
it('adds suppression when already present', function () { | |
const stack = new Stack(); | |
const bucket = new Bucket(stack, 'Bucket'); | |
const firstSuppression: CfnNagSuppression = { id: 'my id', reason: 'my reason' }; | |
const secondSuppression: CfnNagSuppression = { id: 'another id', reason: 'another reason' }; | |
(bucket.node.defaultChild as CfnResource).cfnOptions.metadata = { | |
cfn_nag: { rules_to_suppress: [firstSuppression] }, | |
}; | |
addCfnNagSuppression(bucket, secondSuppression); | |
expect((bucket.node.defaultChild as CfnResource).cfnOptions.metadata?.cfn_nag?.rules_to_suppress).toStrictEqual( | |
expect.arrayContaining([firstSuppression, secondSuppression]), | |
); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment