Skip to content

Instantly share code, notes, and snippets.

@jgillich
Last active August 29, 2015 14:05
Show Gist options
  • Save jgillich/202712747161d5e8da2f to your computer and use it in GitHub Desktop.
Save jgillich/202712747161d5e8da2f to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
'''
JavaScript Renderer for Salt
Example SLS file:
#!js
module.exports.wget = function () {
return { pkg: ['installed'] };
};
Note that the code is executed with node -e - there is no __filename, __dirname and no way to include local modules.
You can either export a JSON or an object containing objects/functions returning objects.
'''
from __future__ import absolute_import
# Import python libs
import subprocess
import json
# Import salt libs
from salt._compat import string_types
def render(js, saltenv='base', sls='', **kws):
if not isinstance(js, string_types):
js = js.read()
if js.startswith('#!'):
js = js[(js.find('\n') + 1):]
js = """var data =
(function (exports, module) {
""" + js + """
return Object.keys(exports).length && exports || module && module.exports || {};
}({}, { exports: {} }));
if(typeof data === 'object') {
for(var k in data) {
switch(typeof data[k]) {
case 'function': data[k] = data[k](); break;
}
}
data = JSON.stringify(data);
}
console.log(data);
"""
output = subprocess.check_output(["node", "-e", js])
return json.loads(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment