Reputation: 2115
I have a shell command in ansible, that changes some file. But most of the time, file stays the same.
What is a preferred way to compare the content of the file before/after shell command and set task changed
property?
Upvotes: 1
Views: 1434
Reputation: 67984
Q: "Compare the content of the file before/after the shell command and set task changed."
A: Make the script report the changes, register the output of the shell command, and test changed_when.
For example, the task below sets a random environment variable RANDOM_TEXT and writes it to the file /tmp/test.ansible. If the file changes the script will report changed. Because of the potentially failing diff you have to set ignore_errors: true
- shell: "sh -c 'cp /tmp/test.ansible /tmp/test.ansible.orig;
echo $RANDOM_TEXT > /tmp/test.ansible;
if (diff /tmp/test.ansible.orig /tmp/test.ansible > /dev/null);
then echo not changed;
else echo changed;
fi'"
environment:
RANDOM_TEXT: "{{ lookup('random_choice', 'AAA', 'BBB') }}"
ignore_errors: true
register: result
changed_when: result.stdout == 'changed'
Example of a complete playbook for testing
- hosts: localhost
tasks:
- shell: "sh -c 'cp /tmp/test.ansible /tmp/test.ansible.orig;
echo $RANDOM_TEXT > /tmp/test.ansible;
if (diff /tmp/test.ansible.orig /tmp/test.ansible > /dev/null);
then echo not changed;
else echo changed;
fi'"
environment:
RANDOM_TEXT: "{{ lookup('random_choice', 'AAA', 'BBB') }}"
ignore_errors: true
register: result
changed_when: result.stdout == 'changed'
- debug:
var: result
Upvotes: 1