Ansible synchronize always sets changed

Viewed 1220

I need to set the contents of a dest folder to be the same as my src folder. So I am using the synchronize module:

- name: files for /lib/user/ based on the Runtime version
  synchronize:
    src: "/data/managedFiles/lib/{{ runtime.version }}/user/"
    dest: "{{ mule_directory }}{{ mule_runtime_name }}/lib/user/"
    delete: yes
  register: result

But this sets "changed" to 'true' in result, even when there was no change. I need this to be only set to 'true' if there was a something changed because the next task tests for this state.

If I repeat the same synchronize task right after this one it doesn't set 'changed' to 'true'. But that one always doesn't get set to 'true'.

Subsequent runs of the play with no change to the src ("/data/managedFiles/lib/{{ runtime.version }}/user/") always set result with 'changed'.

2 Answers

By default, the timestamps of the files are included in the test that detects when to copy the files. Since the files are being pulled from git, the timestamps are different on each play creating a false signal. But not when the same synchronize is run twice in a row. The solution is to set checksum parameter to yes so that timestamps are not checked. But this requires also setting the recursive and archive parameters:

- name: files for /lib/user/ based on the Runtime version
  synchronize:
    src: "/data/managedFiles/lib/{{ runtime.version }}/user/"
    dest: "{{ mule_directory }}{{ mule_runtime_name }}/lib/user/"
    recursive: yes
    archive: no
    checksum: yes
    delete: yes
  register: result

You can have some pre-condition like this:


- name: check dest directory exists 
  stat:
     path: {{ mule_directory }}{{ mule_runtime_name }}/lib/user/
  register: exist_dir


- name: files for /lib/user/ based on the Runtime version
  synchronize:
    src: "/data/managedFiles/lib/{{ runtime.version }}/user/"
    dest: "{{ mule_directory }}{{ mule_runtime_name }}/lib/user/"
    delete: yes
  when: not exist_dir.stat.exists
  register: result

or

- name: Check whether {{ runtime.version }} exists somewhere in one of the file
  command: grep -Fxq "{{ runtime.version }}"    "{{ mule_directory }}{{ mule_runtime_name }}/lib/user/"
  register: checkversion
  check_mode: no
  ignore_errors: yes
  changed_when: no

- name: files for /lib/user/ based on the Runtime version
  synchronize:
    src: "/data/managedFiles/lib/{{ runtime.version }}/user/"
    dest: "{{ mule_directory }}{{ mule_runtime_name }}/lib/user/"
    delete: yes
  when: checkversion.rc != 0
Related