Centos – How to check if two files are identical on the same host with ansible

ansiblecentos

I use Ansible to manage nodes, and I want to check timezone on my nodes.

I find that on centos, I should replace /etc/localtime by according /usr/share/zoneinfo/{{ timezone }} file.

I write thi task in my ansible playbook :

- name: sync timezone file if different
  command: "rsync --itemize-changes --checksum --copy-links /usr/share/zoneinfo/{{ timezone }} /etc/localtime"

which works.

My goal is to perform action only if it's necessary, so with this, localtime will be write only if something's changed.

But my problem is that I also want to use Ansible to check any changed on my nodes. And when ansible perform a command, it always marked in report "changed=1", even if there is no change.

I try to use a file modules of ansible, but whether it's to copy remote to local or local to remote, but not remote to remote.

I also try to use a check with register option with this task :

- name: Copy timezone {{ timezone }} to /etc/localtime
  shell: "[[ $(md5sum /usr/share/zoneinfo/Europe/Paris | cut -d' ' -f1) = $(md5sum /etc/localtime | cut -d' ' -f1) ]]"
  register: timezone_check

But that's the same problem, command is always execute, so changed is incremented.

Any idea how I could perform this ?

Best Answer

It is possible to override the changed result.

In your case, you can check the result of your shell command and override the changed status as appropriate.

Full task with override change result :

- name: Check timezone conf
  command: "rsync --itemize-changes --checksum --copy-links /usr/share/zoneinfo/{{ timezone }} /etc/localtime"
  register: timezone_check
  changed_when: "timezone_check.stdout.find('>') != -1"
  become: yes