pass json to exec templates on stdin.

remove code for passing input params as environment variables.
This commit is contained in:
Tim Miller 2013-01-29 13:32:23 -08:00
parent 7e89aaa6b1
commit d40094e2bd
3 changed files with 14 additions and 26 deletions

View File

@ -3,10 +3,11 @@ import json
import logging
import os
import pystache
import subprocess
import sys
import tempfile
from optparse import OptionParser
from pystache.context import KeyNotFoundError
from subprocess import Popen, PIPE
logging.basicConfig(format='[%(asctime)s] [%(levelname)s] %(message)s', datefmt='%Y/%m/%d %I:%M:%S %p', level=logging.INFO)
@ -49,10 +50,11 @@ def render_moustache(text, config):
return r.render(text, config)
def render_executable(path, config):
try:
return subprocess.check_output([path], env=flatten(config))
except subprocess.CalledProcessError as e:
raise CornfigException("config script failed: %s\n\nwith output:\n\n%s" % (path, e.output))
p = Popen([path], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(json.dumps(config))
p.wait()
if p.returncode != 0: raise CornfigException("config script failed: %s\n\nwith output:\n\n%s" % (path, stdout + stderr))
return stdout
def read_config(path):
try:
@ -60,20 +62,6 @@ def read_config(path):
except:
raise CornfigException("invalid metadata file: %s" % path)
# flatten a nested hash into a one-level hash
# {x: {a: b} } => {x.a: b}
def flatten(d, prefix='', res=None):
res = res or {}
for k, v in d.items():
key = (prefix + '.' + k) if len(prefix) > 0 else k
if isinstance(v, str) or isinstance(v, unicode):
res[key] = v
elif isinstance(v, dict):
res = dict(res.items() + flatten(v, key, res).items())
else:
raise CornfigException("expected only strings and hashes in config.")
return res
# given a root directory, return a list of tuples
# containing input and output paths
def template_paths(root):

View File

@ -49,9 +49,6 @@ def test_install_cornfig():
def test_build_tree():
assert_equals( build_tree(template_paths(TEMPLATES), CONFIG), OUTPUT )
def test_flatten():
assert_equals( flatten({"x": {"a": "b", "c": "d"}, "y": "z"}), {"x.a": "b", "x.c": "d", "y": "z"} )
def test_render_template():
# execute executable files, moustache non-executables
assert render_template(template("/etc/glance/script.conf"), {"x": "abc"}) == "abc\n"

View File

@ -1,4 +1,7 @@
#!/bin/sh
set -u
echo $x
#!/usr/bin/env python
import json
import sys
params = json.loads(sys.stdin.read())
x = params["x"]
if x is None: raise Exception("undefined: x")
print x