Skip to content

Instantly share code, notes, and snippets.

@rnhurt
Created April 4, 2015 15:24
Show Gist options
  • Save rnhurt/0a63f03e35495106357d to your computer and use it in GitHub Desktop.
Save rnhurt/0a63f03e35495106357d to your computer and use it in GitHub Desktop.
Cloud Formation Templates
#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var hbs = require('handlebars');
var globals = JSON.parse(fs.readFileSync(__dirname+'/templates/common/globals.json'));
// Register Handlebars "helpers"
hbs.registerHelper('toLowerCase', function (str) { return str.toLowerCase(); });
hbs.registerHelper('toUpperCase', function (str) { return str.toUpperCase(); });
hbs.registerHelper('findAMI', function (ami, context) { return context.AMIs[ami]; });
hbs.registerHelper('ifIn', function (elem, list, options) {
if(list.indexOf(elem) > -1) {
return options.fn(this);
}
return options.inverse(this);
});
hbs.registerHelper('include', function (file, context, options) {
var context = null == context ? args : context;
var f = fs.readFileSync(file);
return process_file(f, context);
});
hbs.registerHelper('lookupById', function (collection, id) {
var collectionLength = collection.length;
for (var i = 0; i < collectionLength; i++) {
if (collection[i].Id === id) {
return collection[i];
}
}
return null;
});
// Compile a Handlebars template and run it
function process_file(tmpl, args) {
var template = hbs.compile(tmpl.toString());
var result = template(args);
return result;
}
// Prepare the file system
fs.mkdir(__dirname+'/artifacts/cloudformation', function(err){});
process.chdir(__dirname+'/templates');
// Get all of the project files
fs.readdir('projects', function(err, files) {
if(err) throw err;
// Loop through each 'project' file
files.forEach(function(file){
// Only process handlebars templates
if (path.extname(file) != '.hbs') return;
// Process the file and build the final template
fs.readFile('projects/' + file, {encoding: 'utf-8'}, function(err, tmpl){
console.log('Processing ' + file);
var context = JSON.parse(process_file(tmpl, globals));
fs.readFile(context['Template'], {encoding: 'utf-8'}, function(err, tmpl2){
// Combine the template context with the 'global' context
var master={};
for(var key in context) master[key]=context[key];
for(var key in globals) master[key]=globals[key];
// Build the final output and compute a file name
var template = process_file(tmpl2, master);
var output_name = (context['ProjectName'] + '.' + context['EnvType'] + '.template').toLowerCase();
// Write out the CloudFormation template
fs.writeFile(__dirname+'/artifacts/cloudformation/'+output_name, template, function(err){
if (err) throw err;
})
// process.stdout.write(template);
});
});
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment