Created
July 4, 2018 08:47
-
-
Save thomasmichaelwallace/aef267a1e3b9fbf5095364f297493952 to your computer and use it in GitHub Desktop.
Synchronise CloudWatch dashboards
This file contains hidden or 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 util from 'util'; | |
import AWS from 'aws-sdk'; | |
// command options | |
const OPT_NAME = 'my-first-dashboard'; // name of dashboard to sync. | |
const OPT_TEMPLATE = 'master'; // environment to sync-from. | |
// dashboard/environment options | |
const asName = (name, environment) => `${name}-${environment}`; // template for full dashboard name. | |
const environments = ['master', 'staging', 'production']; // environments to duplicate across | |
const cloudwatch = new AWS.CloudWatch(); | |
const getDashboardJson = (name, environment) => | |
cloudwatch | |
.getDashboard({ DashboardName: asName(name, environment) }) | |
.promise() | |
.then(({ DashboardBody }) => DashboardBody); | |
const putDashboardJson = (name, DashboardBody, environment) => | |
cloudwatch | |
.putDashboard({ DashboardName: asName(name, environment), DashboardBody }) | |
.promise() | |
.then(() => console.log(`Created ${asName(name, environment)} successfully.`)); | |
const switchEnvironment = (dashBoard, fromEnvironment, toEnvironment) => { | |
replacements.push({ find: fromEnvironment, replace: toEnvironment }); | |
let switched = dashBoard; | |
replacements.forEach(({ find, replace }) => { | |
switched = switched.replace(new RegExp(find, 'g'), replace); | |
}); | |
return switched; | |
}; | |
const updateDashboard = (name, fromEnvironment, toEnvironment) => { | |
console.log(`Updating dashboard ${asName(name, toEnvironment)} from template ${fromEnvironment}`); | |
getDashboardJson(name, fromEnvironment) | |
.then((dashBoard) => { | |
const updated = switchEnvironment(dashBoard, fromEnvironment, toEnvironment); | |
return putDashboardJson(name, updated, toEnvironment); | |
}) | |
.catch(error => console.error(`Failed to update as ${util.inspect(error)}`)); | |
}; | |
const updateDashboards = (name, master) => | |
environments | |
.filter(e => e !== master) | |
.map(e => updateDashboard(name, master, e)); | |
updateDashboards(OPT_NAME, OPT_TEMPLATE); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment