To create a CloudWatch Dashboard in CloudFormation, you must supply the dashboard's source code as a stringified JSON rather than as a separate JSON structure.
This is annoying because my JSON has to be escaped inside of a string literal within my serverless.yml
:
...
resources:
Resources:
MyDashboard:
Type: AWS::CloudWatch::Dashboard
Properties:
DashboardName: My-Dashboard
DashboardBody: "{\"widgets\": [...]}"
I tried using a file reference:
...
resources:
Resources:
MyDashboard:
Type: AWS::CloudWatch::Dashboard
Properties:
DashboardName: My-Dashboard
DashboardBody: ${file(my-dashboard.json)}
but serverless
inserts the content as part of the YAML structure, rather than as part of the JSON string:
...
resources:
Resources:
MyDashboard:
Type: AWS::CloudWatch::Dashboard
Properties:
DashboardName: My-Dashboard
DashboardBody:
Widgets:
- ...
- ...
Is there a way to stringify
the JSON from my-dashboard.json
?
The following steps are needed to create a CloudWatch dashboard with a custom resource. Create a CloudFormation template and add a Lambda-backed custom resource. Write the code creating, updating, and deleting a CloudWatch dashboard. Generate the JSON code describing the customized dashboard.
To create a dashboard from the consoleOpen the CloudWatch console at https://console.aws.amazon.com/cloudwatch/ . In the navigation pane, choose Dashboards, and then choose Create dashboard. In the Create new dashboard dialog box, enter a name for the dashboard, and then choose Create dashboard.
Custom widgets allow you to extend your CloudWatch dashboards' out of the box capabilities including line, bar and pie charts with rich, business specific visualizations that represent the operational health and performance of your workloads. This feature is available in the following AWS Regions: US East (N.
A dashboard is a customizable home page in the CloudWatch console that you can use to monitor your AWS resources in a single view. All dashboards in your account are global, not region-specific.
There doesn't appear to be a way stringify
JSON directly within a serverless variable. However, you can reference an external .js
file, and then stringify
the .json
file there:
serverless.yml
:
...
resources:
Resources:
MyDashboard:
Type: AWS::CloudWatch::Dashboard
Properties:
DashboardName: My-Dashboard
DashboardBody: ${file(my-dashboard-body.js):myDashboardBody}
${file(my-dashboard-body.js):myDashboardBody}
is a serverless variable reference. It means that we want to use the value from the myDashboardBody
module of the my-dashboard-body.js
file.
my-dashboard-body.js
:
module.exports.myDashboardBody = (serverless) => {
const fsPromises = require('fs').promises
return fsPromises.readFile('my-dashboard-body.json', 'utf-8')
};
my-dashboard-body.json
:
{
"widgets": [
...
]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With