terraform-plus
Version:
Terraform Plus
118 lines (102 loc) • 3.26 kB
JavaScript
'use strict';
const { exec } = require('child_process');
// const path = require('path');
const fs = require('fs');
const yaml = require('js-yaml');
const treeify = require('treeify');
const ProgressBar = require('progress');
const TerraformCommand = require('../terraform-command');
const Terraform = require('../terraform/terraform');
class InitCommand extends TerraformCommand {
/**
* @desc Validates options passed via cli
*
* @returns {Boolean} - Returns true if options given from cli are valid.
*
* @private
*/
_validateOptions() {
this._logger.debug(`this._cli : ${this._cli}`);
return super._validateOptions();
}
/**
* @desc Executes `terraform init` across multiple terraform scripts
*/
run() {
//let promiseArray = [];
if (!this._validateOptions()) {
process.exit(1);
}
let filesPath = this.getFilesPath([this._directory]);
this._layers=[[]];
this._logger.debug(`templates : ${this.templates}`);
this._folders = {};
this._graph = {};
this.getFilesPath([this._directory]).forEach(element => {
if (fs.existsSync(element)) {
let tfsConf = yaml.safeLoad(fs.readFileSync(`${element}/${this._paramFile}`, 'utf8'));
this._folders[tfsConf.id] = element;
if (tfsConf && tfsConf.parent) {
this._graph[tfsConf.id] = tfsConf.parent ;
} else {
if (!this._graph[tfsConf.id]) {
this._graph[tfsConf.id] = null;
this._layers[0].push(tfsConf.id);
}
}
}
});
console.log('Building tree:');
let graph = this._graph;
//let bar = this.bar;
if (this._cli.branch) {
graph = this.findBranch(this._graph);
console.log(treeify.asTree(this.listToTree(graph), true));
} else {
console.log(treeify.asTree(this.listToTree(graph), true));
}
if (!this._verbose) {
this.bar = new ProgressBar('Run init [:bar] :percent :elapseds',
{ total: Object.keys(graph).length, width: 30 });
this.bar.tick(0);
}
let tf = this.terraform();
// executes terraform init for each dir that has .tf files
filesPath.forEach((element) => {
tf.then((terraform) => {
terraform.setLoggerLevel(this._logger.getLevel());
terraform.init(element).then(() => {
if (!this._verbose) {
this.bar.tick();
}
});
});
});
return Promise.resolve();
}
/**
* @returns {String}
*/
static get DESCRIPTION() {
return 'run `terraform init` across multiple terraform scripts'
}
/**
* @returns {Array}
*/
static get OPTIONS() {
return [{
opt: '-p, --provider <provider>',
desc: 'terraform provider name (e.g. aws, azurerm, google)'
}, {
opt: '-i, --include [comma_separated_values]',
desc: 'comma separated values of terraform scripts or folders to be included'
}, {
opt: '-e, --exclude [comma_separated_values]',
desc: 'comma separated values of terraform scripts or folders to be excluded'
}, {
opt: '-d, --directory [directory]',
desc: 'path where terraform will be executed (default value - current working directory)'
}];
}
}
module.exports = InitCommand;