Ensuring CDK Resource Properties
Problem
Using CDK v2, I wanted to ensure all of my lambda functions had the nodejs14.x
runtime. I knew I could ensure that at least one resource was created with the desired property using the aws-cdk-lib/assertions
package like this:
describe('lambdas',() => {
test('should all have NodeJS14.x runtime', () => {
const app = new cdk.App();
const stack = new MyStack(app, 'MyTestStack');
template = Template.fromStack(stack);
// false positive: this passes the test
// because at least one matching resource is created
template.hasResourceProperties('AWS::Lambda::Function', {
Runtime: 'nodejs14.x'
})
});
});
UPDATE 8/7: Previously, I tried leveraging the allResourcesHaveProperty()
method on Template
, but I didn't capture the correct results.
The solution is to leverage the Capture
object to record values for entries matching the expected properties in the template:
describe('lambdas',() => {
test('should all have NodeJS14.x runtime', () => {
const app = new cdk.App();
const stack = new MyStack(app, 'MyTestStack');
template = Template.fromStack(stack);
// capture the Runtime configuration of all Lambdas
const runtimeCapture = new Capture();
template.hasResourceProperties('AWS::Lambda::Function', {
Runtime: runtimeCapture
});
let captureCount = 0;
while (runtimeCapture.next()) {
captureCount++;
// we should have captured the correct runtime for each resource captured
expect(runtimeCapture.asString()).toBe('nodejs14.x');
}
// we should have at least one lambda resource
expect(captureCount).toBeGreaterThan(0);
})
})
packages:
"devDependencies": {
"@types/jest": "^27.5.2",
"@types/node": "10.17.27",
"aws-cdk": "2.33.0",
"jest": "^27.5.1",
"ts-jest": "^27.1.4",
"ts-node": "^10.9.1",
"typescript": "~3.9.7"
},
"dependencies": {
"aws-cdk-lib": "2.33.0",
"constructs": "^10.0.0",
"esbuild": "^0.14.50",
}
Like this article?
1
Software Development Nerd