Skip to content

Commit f53f845

Browse files
Jimmy GaussenElad Ben-Israel
authored andcommitted
feat(cloudwatch): dashboardName validation (#3382)
Fixes #2976
1 parent 5a6aff0 commit f53f845

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

packages/@aws-cdk/aws-cloudwatch/lib/dashboard.ts

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Construct, Lazy, Resource, Stack } from "@aws-cdk/core";
1+
import { Construct, Lazy, Resource, Stack, Token } from "@aws-cdk/core";
22
import { CfnDashboard } from './cloudwatch.generated';
33
import { Column, Row } from "./layout";
44
import { IWidget } from "./widget";
@@ -10,9 +10,11 @@ export enum PeriodOverride {
1010

1111
export interface DashboardProps {
1212
/**
13-
* Name of the dashboard
13+
* Name of the dashboard.
1414
*
15-
* @default Automatically generated name
15+
* If set, must only contain alphanumerics, dash (-) and underscore (_)
16+
*
17+
* @default - automatically generated name
1618
*/
1719
readonly dashboardName?: string;
1820

@@ -67,6 +69,16 @@ export class Dashboard extends Resource {
6769
physicalName: props.dashboardName,
6870
});
6971

72+
{
73+
const {dashboardName} = props;
74+
if (dashboardName && !Token.isUnresolved(dashboardName) && !dashboardName.match(/^[\w-]+$/)) {
75+
throw new Error([
76+
`The value ${dashboardName} for field dashboardName contains invalid characters.`,
77+
'It can only contain alphanumerics, dash (-) and underscore (_).'
78+
].join(' '));
79+
}
80+
}
81+
7082
new CfnDashboard(this, 'Resource', {
7183
dashboardName: this.physicalName,
7284
dashboardBody: Lazy.stringValue({ produce: () => {

packages/@aws-cdk/aws-cloudwatch/test/test.dashboard.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,24 @@ export = {
149149
// THEN
150150
expect(stack).to(haveResource('AWS::CloudWatch::Dashboard', {}));
151151

152+
test.done();
153+
},
154+
155+
'throws if DashboardName is not valid'(test: Test) {
156+
// GIVEN
157+
const app = new App();
158+
const stack = new Stack(app, 'MyStack');
159+
160+
// WHEN
161+
const toThrow = () => {
162+
new Dashboard(stack, 'MyDashboard', {
163+
dashboardName: 'My Invalid Dashboard Name',
164+
});
165+
};
166+
167+
// THEN
168+
test.throws(() => toThrow(), /field dashboardName contains invalid characters/);
169+
152170
test.done();
153171
}
154172
};

0 commit comments

Comments
 (0)