Output useful JSON data

If you use os-apply-config to slice out a JSON blob on the command
line you'll get back a string formatted dump of a python
dictionary (or list). Ideally we would print out proper JSON text
so that other tooling (jq, etc) can post process things in a
useful manner.

This patch updates apply_config so that if an output key is
detected to be a dict or a list it is printed to stdout
in a JSON format.

Change-Id: Ibc8b21cd6922b8664ca71e9e6009c8573ea9d107
This commit is contained in:
Dan Prince 2014-12-16 09:42:24 -05:00
parent b4c5ee5995
commit fcb3d0f96f
2 changed files with 22 additions and 1 deletions

View File

@ -102,7 +102,10 @@ def print_key(
raise exc.ConfigException(
'key %s does not exist in %s' % (key, config_path))
value_types.ensure_type(str(config), type_name)
print(str(config))
if isinstance(config, (dict, list)):
print(json.dumps(config))
else:
print(str(config))
def write_file(path, obj):

View File

@ -112,6 +112,24 @@ class TestRunOSConfigApplier(testtools.TestCase):
self.stdout.read().strip())
self.assertEqual('', self.logger.output)
def test_print_key_json_dict(self):
self.assertEqual(0, apply_config.main(
['os-apply-config.py', '--metadata', self.path, '--key',
'database', '--type', 'raw']))
self.stdout.seek(0)
self.assertEqual(CONFIG['database'],
json.loads(self.stdout.read().strip()))
self.assertEqual('', self.logger.output)
def test_print_key_json_list(self):
self.assertEqual(0, apply_config.main(
['os-apply-config.py', '--metadata', self.path, '--key',
'l', '--type', 'raw']))
self.stdout.seek(0)
self.assertEqual(CONFIG['l'],
json.loads(self.stdout.read().strip()))
self.assertEqual('', self.logger.output)
def test_print_non_string_key(self):
self.assertEqual(0, apply_config.main(
['os-apply-config.py', '--metadata', self.path, '--key',