Ansible Module Diff Mode Behavior

I’m using a custom Ansible module that supports diff mode. The module returns the result in the following format:

"diff": {
        "after": {},
        "before": {}
}

I have a query regarding the list attribute named temp . Initially, the list attribute is empty. When I add one element, the list becomes ["item1"] , which is expected.
However, when I add a second element (item2 ) to the list, the diff output is as follows:

--- before
+++ after
"temp": [
-    "item1"
+    "item1",
+    "item2"
 ]

It appears that both item1 and item2 are being shown as added, even though only item2 was newly added. Is this the expected behavior?

I’d say yes, it’s expected (but some of the devs could confirm). The diff works by pretty printing a JSON formated values of “after” and “before”. After that, a standard line by line diff is called. Just like if you used diff command in a shell.

In your particular case, the diff shows "item1" line changed because a comma is added to the line.

In short, this is a text based diff, not an object structure aware diff.

2 Likes

I think whether the diff is formatted as JSON or something else depends on the callback plugin (IIRC the YAML callback formats them as YAML). So basically if you don’t like the default diff representation, you can write a callback which formats it the way you want :slight_smile:

(I’d personally use JSON with trailing commas, even though that’s not proper JSON, or YAML, but I’m usually too lazy to change the callback so I stick to the default :wink: )

1 Like