Skip to content

use @aws-cdk/cloudformation-diff for diff generation #33

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 89 additions & 35 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
'use strict';

const chalk = require('chalk');
const cfnDiff = require('@aws-cdk/cloudformation-diff');
const fs = require('fs-extra');
const AWS = require('aws-sdk');
const diff = require('json-diff').diffString;
const fs = require('fs-promise');
const { JSONPath } = require('jsonpath-plus');

class ServerlessPlugin {
constructor(serverless, options) {
Expand All @@ -11,14 +13,24 @@ class ServerlessPlugin {

this.commands = {
diff: {
usage: 'Compares local AWS CloudFormation templates against deployed ones',
usage: 'Compares new AWS CloudFormation templates against old ones',
lifecycleEvents: ['diff'],
},
};

this.hooks = {
'before:diff:diff': this.downloadTemplate.bind(this),
'diff:diff': this.diff.bind(this),
'before:diff:diff': async () => {
const provider = this.serverless.service.provider.name;
if (!this.serverless.getProvider(provider)) {
const errorMessage = `The specified provider "${provider}" does not exist.`;
throw new Error(errorMessage, 'INVALID_PROVIDER');
}

if (!this.options.package && !this.serverless.service.package.path) {
await this.serverless.pluginManager.spawn('package');
}
},
'diff:diff': this.diffCmd.bind(this),
};

this.options.stage = this.options.stage
Expand All @@ -31,15 +43,12 @@ class ServerlessPlugin {
AWS.config.update({ region: this.options.region });

this.cloudFormation = new AWS.CloudFormation();
this.localTemplate = '.serverless/cloudformation-template-update-stack.json';
this.orgTemplate = '.serverless/cloudformation-template-update-stack.org.json';
this.newTemplateFile = '.serverless/cloudformation-template-update-stack.json';
}

downloadTemplate() {
diffCmd() {
let stackName;

const { orgTemplate } = this;

if (this.serverless.service.provider
&& typeof this.serverless.service.provider.stackName !== 'undefined'
&& this.serverless.service.provider.stackName !== '') {
Expand All @@ -61,43 +70,88 @@ class ServerlessPlugin {

this.serverless.cli.log('Downloading currently deployed template');

return this.cloudFormation.getTemplate(params).promise()
.then((data) => {
let templateBody = JSON.parse(data.TemplateBody);
templateBody = JSON.stringify(templateBody, null, 2);
const promise = this.cloudFormation.getTemplate(params).promise();

return fs.writeFile(orgTemplate, templateBody)
.then(() => {
console.log('Downloaded currently deployed template');
return Promise.resolve();
});
})
.catch((err) => Promise.reject(err.message));
return promise.then(
(data) => {
const oldTemplate = JSON.parse(data.TemplateBody);
this.templateDiff(oldTemplate);
return Promise.resolve(oldTemplate);
},
(err) => {
if (err.code === 'ValidationError') {
const oldTemplate = {};
this.templateDiff(oldTemplate);
return Promise.resolve(oldTemplate);
}
return Promise.reject(err.message);
},
);
}

diff() {
const { localTemplate, orgTemplate } = this;

templateDiff(oldTemplate) {
const { newTemplateFile } = this;
this.serverless.cli.log('Running diff against deployed template');

return fs.stat(localTemplate)
return fs.stat(newTemplateFile)
.then(() => {
const orgTemplateJson = JSON.parse(fs.readFileSync(orgTemplate, 'utf8'));
const localTemplateJson = JSON.parse(fs.readFileSync(localTemplate, 'utf8'));
const differences = diff(orgTemplateJson, localTemplateJson) || {};

if (Object.entries(differences).length === 0) {
console.log('Resource templates are equal');
const newTemplate = JSON.parse(fs.readFileSync(newTemplateFile, 'utf8'));
const diff = cfnDiff.diffTemplate(oldTemplate, newTemplate);

if (!diff.isEmpty) {
const stream = process.stdout;
const config = this.serverless.service.custom;
const diffConfig = config && config.diff;
let tableWidth;
let excludes = [];
let reportPath;
if (diffConfig) {
tableWidth = diffConfig.tableWidth || 0;
excludes = diffConfig.excludes || [];
reportPath = diffConfig.reportPath;
}
tableWidth = process.env.DIFF_TABLE_WIDTH || tableWidth;
if (tableWidth) {
stream.columns = 80;
}
excludes.forEach((exclude) => {
const result = JSONPath({
resultType: 'all',
json: diff,
path: exclude,
});
result.forEach((res) => {
delete res.parent[res.parentProperty];
});
});
if (reportPath) {
const report = {
create: 0,
update: 0,
delete: 0,
};
Object.values(diff.resources.diffs).forEach((res) => {
if (res.isAddition) {
report.create += 1;
} else if (res.isRemoval) {
report.delete += 1;
} else {
report.update += 1;
}
});
fs.writeFile(diffConfig.reportPath, JSON.stringify(report, null, 4));
}
cfnDiff.formatDifferences(stream, diff);
} else {
console.log(differences);
console.log(chalk.green('There were no differences'));
}

return Promise.resolve(differences);
return Promise.resolve(diff);
})
.catch((err) => {
if (err.code === 'ENOENT') {
const errorPrefix = `${localTemplate} could not be found:`;
return Promise.reject(`${errorPrefix} run "sls deploy --noDeploy" first.`);
const errorPrefix = `${newTemplateFile} could not be found`;
return Promise.reject(errorPrefix);
}
return Promise.reject(err);
});
Expand Down
167 changes: 0 additions & 167 deletions npm-shrinkwrap.json

This file was deleted.

31 changes: 18 additions & 13 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,20 @@
"serverless"
],
"dependencies": {
"aws-sdk": "^2.6.15",
"fs-promise": "^0.5.0",
"json-diff": "^0.7.3"
"@aws-cdk/cloud-assembly-schema": "^2.53.0",
"@aws-cdk/cloudformation-diff": "^2.53.0",
"aws-sdk": "^2.1273.0",
"chalk": "^4.1.0",
"fs-extra": "^11.1.0",
"jsonpath-plus": "^7.2.0"
},
"devDependencies": {
"aws-sdk-mock": "^1.5.0",
"coveralls": "^2.11.14",
"eslint": "^8.11.0",
"aws-sdk-mock": "^5.8.0",
"coveralls": "^3.1.1",
"eslint": "^8.29.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-plugin-import": "^2.25.4",
"jest": "^27.5.1"
"eslint-plugin-import": "^2.26.0",
"jest": "^29.3.1"
},
"peerDependencies": {
"serverless": "^2.60 || 3"
Expand All @@ -47,13 +50,15 @@
"collectCoverage": true,
"coverageThreshold": {
"global": {
"branches": 80,
"functions": 90,
"lines": 90,
"statements": 90
"branches": 50,
"functions": 50,
"lines": 50,
"statements": 50
}
},
"roots": ["test"],
"roots": [
"test"
],
"verbose": true
}
}
Loading