Skip to content


Browse files Browse the repository at this point in the history
Added variables to command line utility #39
  • Loading branch information
nemesifier committed Feb 16, 2016
1 parent bb00efd commit a3486d2
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 1 deletion.
4 changes: 3 additions & 1 deletion bin/netjsonconfig
@@ -1,5 +1,6 @@
#!/usr/bin/env python

import os
import sys
import six
import argparse
Expand Down Expand Up @@ -143,6 +144,7 @@ def print_output(output):
args = parser.parse_args()
config = _load(args.config)
templates = [_load(template) for template in args.templates]
context = dict(os.environ)
method = args.method
method_arguments = parse_method_arguments(args.args)

Expand All @@ -153,7 +155,7 @@ backends = {

backend_class = backends[args.backend]
instance = backend_class(config, templates=templates)
instance = backend_class(config, templates=templates, context=context)
except TypeError as e:
print('netjsonconfig: invalid JSON passed in config or templates')
Expand Down
2 changes: 2 additions & 0 deletions docs/source/general/basics.rst
Expand Up @@ -271,6 +271,8 @@ it's possible to pass multiple templates that will be added one on top of the
other to build the resulting *configuration dictionary*, allowing to reduce or
even eliminate repetitions.

.. _configuration_variables:

Context: configuration variables

Expand Down
14 changes: 14 additions & 0 deletions docs/source/general/commandline_utility.rst
Expand Up @@ -67,3 +67,17 @@ Here's the common use cases explained::
Using templates::

netjsonconfig -c config.json -t template1.json template2.json -b openwrt -m render

Environment variables

*Environment variables* are automatically passed to the ``context`` argument (if you don't
know what this argument does please read ":ref:`configuration_variables`"), therefore
you can reference environment variables inside *configurations* and *templates*::

export HOSTNAME=freedom
netjsonconfig -c '{"general": { "hostname": "${HOSTNAME}" }}' -b openwrt -m render

You can also avoid using ``export`` and write everything in a one line command::

PORT=2009; netjsonconfig -c config.json -t template1.json -b openwrt -m render
7 changes: 7 additions & 0 deletions tests/
Expand Up @@ -121,3 +121,10 @@ def test_generate_redirection(self):
tar ='test.tar.gz', 'r')
self.assertEqual(len(tar.getmembers()), 1)

def test_context(self):
config = json.dumps({'general': {'description': '${DESC}'}})
command = "export DESC=testdesc; netjsonconfig --config '{0}' -b openwrt -m render".format(config)
output = subprocess.check_output(command, shell=True).decode()
self.assertNotIn('${DESC}', output)
self.assertIn('testdesc', output)

0 comments on commit a3486d2

Please sign in to comment.