What I do when I've a command to execute and wish to get the log only in case of failure is as follow (prefixed by a shell comamnd like
/bin/sh -c '...' in case the initiator doesn't use a
system call or execute the command directly without shell):
command 2&>1 > command-log.txt || cat command-log.txt
This will redirect error and standard output to a file and display the content of the file in case of failure only. If the command is very verbose and you don't wish to keep the log when it's ok you can go with:
command 2&>1 > command-log.txt && rm command-log.txt || cat command-log.txt
|| usage from sh manpage:
The symbol && (||) causes the list following to be executed only if
the preceding pipeline returns a zero (non zero) value.
That's probably not the most idiomatic way to do it with ansible but has the advantage of being very portable with any configuration management system giving the ability to display command stdout.