diff --git a/changelogs/fragments/62582-allow_diff_before_after_to_be_None.yml b/changelogs/fragments/62582-allow_diff_before_after_to_be_None.yml new file mode 100644 index 00000000000..65d9c6b7e18 --- /dev/null +++ b/changelogs/fragments/62582-allow_diff_before_after_to_be_None.yml @@ -0,0 +1,4 @@ +minor_changes: + - callbacks - Allow modules to return `None` as before/after entries for diff. + This should make it easier for modules to report the "not existing" state of + the entity they touched. diff --git a/lib/ansible/plugins/callback/__init__.py b/lib/ansible/plugins/callback/__init__.py index ece3b1862ae..a4d1e30a08a 100644 --- a/lib/ansible/plugins/callback/__init__.py +++ b/lib/ansible/plugins/callback/__init__.py @@ -184,6 +184,8 @@ class CallbackBase(AnsiblePlugin): for x in ['before', 'after']: if isinstance(diff[x], MutableMapping): diff[x] = self._serialize_diff(diff[x]) + elif diff[x] is None: + diff[x] = '' if 'before_header' in diff: before_header = u"before: %s" % diff['before_header'] else: diff --git a/test/units/plugins/callback/test_callback.py b/test/units/plugins/callback/test_callback.py index 52233800f36..906f00040c8 100644 --- a/test/units/plugins/callback/test_callback.py +++ b/test/units/plugins/callback/test_callback.py @@ -365,6 +365,34 @@ class TestCallbackDiff(unittest.TestCase): ''')) + def test_diff_before_none(self): + self.assertMultiLineEqual( + self._strip_color(self.cb._get_diff({ + 'before': None, + 'after': 'one line\n', + })), + textwrap.dedent('''\ + --- before + +++ after + @@ -0,0 +1 @@ + +one line + + ''')) + + def test_diff_after_none(self): + self.assertMultiLineEqual( + self._strip_color(self.cb._get_diff({ + 'before': 'one line\n', + 'after': None, + })), + textwrap.dedent('''\ + --- before + +++ after + @@ -1 +0,0 @@ + -one line + + ''')) + class TestCallbackOnMethods(unittest.TestCase): def _find_on_methods(self, callback):