Skip to content

Instantly share code, notes, and snippets.

@thomasmichaelwallace
Created July 4, 2018 08:47
Show Gist options
  • Save thomasmichaelwallace/aef267a1e3b9fbf5095364f297493952 to your computer and use it in GitHub Desktop.
Save thomasmichaelwallace/aef267a1e3b9fbf5095364f297493952 to your computer and use it in GitHub Desktop.
Synchronise CloudWatch dashboards
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