diff --git a/lib/ansible/runner/filter_plugins/core.py b/lib/ansible/runner/filter_plugins/core.py index 484b059a555..b2431828459 100644 --- a/lib/ansible/runner/filter_plugins/core.py +++ b/lib/ansible/runner/filter_plugins/core.py @@ -18,14 +18,27 @@ import json import yaml +def to_nice_yaml(*a, **kw): + '''Make verbose, human readable yaml''' + return yaml.safe_dump(*a, indent=4, allow_unicode=True, default_flow_style=False, **kw) + +def to_nice_json(*a, **kw): + '''Make verbose, human readable JSON''' + return json.dumps(*a, indent=4, sort_keys=True, **kw) + class FilterModule(object): ''' Ansible core jinja2 filters ''' def filters(self): return { + # json 'to_json': json.dumps, + 'to_nice_json': to_nice_json, 'from_json': json.loads, + + # yaml 'to_yaml': yaml.safe_dump, + 'to_nice_yaml': to_nice_yaml, 'from_yaml': yaml.safe_load, } diff --git a/test/TestFilters.py b/test/TestFilters.py new file mode 100644 index 00000000000..21b6f211755 --- /dev/null +++ b/test/TestFilters.py @@ -0,0 +1,81 @@ +''' +Test bundled filters +''' + +import unittest, tempfile, shutil +from ansible import playbook, inventory, callbacks + +INVENTORY = inventory.Inventory(['localhost']) + +BOOK = ''' +- hosts: localhost + vars: + var: { a: [1,2,3] } + tasks: + - template: src=%s dest=%s +''' + +SRC = ''' +- +{{ var|to_json }} +- +{{ var|to_nice_json }} +- +{{ var|to_yaml }} +- +{{ var|to_nice_yaml }} +''' + +DEST = ''' +- +{"a": [1, 2, 3]} +- +{ + "a": [ + 1, + 2, + 3 + ] +} +- +a: [1, 2, 3] + +- +a: +- 1 +- 2 +- 3 +''' + +class TestFilters(unittest.TestCase): + + def setUp(self): + self.tmpdir = tempfile.mkdtemp(dir='/tmp') + + def tearDown(self): + shutil.rmtree(self.tmpdir) + + def temp(self, name, data=''): + '''write a temporary file and return the name''' + name = self.tmpdir + '/' + name + with open(name, 'w') as f: + f.write(data) + return name + + def test_filters(self): + src = self.temp('src.j2', SRC) + dest = self.temp('dest.txt') + book = self.temp('book', BOOK % (src, dest)) + + playbook.PlayBook( + playbook = book, + inventory = INVENTORY, + transport = 'local', + callbacks = callbacks.PlaybookCallbacks(), + runner_callbacks = callbacks.DefaultRunnerCallbacks(), + stats = callbacks.AggregateStats(), + ).run() + + out = open(dest).read() + self.assertEqual(DEST, out) +