Skip diff if before is empty

Hi,

When using the copy module, I would like to omit the diff output if the destination file does not exist. It seems like the pieces are all there, but they don’t quite fit together.

I wanted to do something like this:

diff: results.diff.before != ''

but I think that results are not available at this point? What’s the easiest way to accomplish this? Prepared to create a custom module if necessary for keeping the playbook simple.

diff: results.diff.before | default('') != ''

See Using filters to manipulate data — Ansible Community Documentation

The default doesn’t help a bit, since the value for diff for the current task is determined before the task is executed, and therefore in it you cannot use data from the result of the current task.

Basically the only way this is possible (with a single task) is through a custom callback plugin, which handles copy tasks specially.

Or you could add a ansible.builtin.stat task first that determines whether the file exists, and set diff accordingly (obviously this has a race condition, assuming someone else creates the file between the ansible.builtin.stat task and the ansible.builtin.copy task).