Hett
Hett

Reputation: 3823

Ansible: How to check files is changed in shell command?

I have file, generated by shell command

- stat: path=/etc/swift/account.ring.gz get_md5=yes
  register: account_builder_stat

- name: write account.ring.gz file
  shell: swift-ring-builder account.builder write_ring <--- rewrite account.ring.gz
    chdir=/etc/swift
  changed_when: ??? account_builder_stat.changed ??? <-- no give desired effect

How can I check that the file has been changed?

Upvotes: 10

Views: 7261

Answers (2)

ady8531
ady8531

Reputation: 678

Following @Kashyap's answer you can also do a diff between the two files but if the two files differ, diff will result in error and it will stop your playbook's run.

Upvotes: -1

Kashyap
Kashyap

Reputation: 17411

- stat: path=/etc/swift/account.ring.gz get_md5=yes
  register: before

- name: write account.ring.gz file
  shell: swift-ring-builder account.builder write_ring # update account.ring.gz
    chdir=/etc/swift
  changed_when: False # without this, as long as swift-ring-builder exits with
                      # return code 0 this task would always be reported as changed

- stat: path=/etc/swift/account.ring.gz get_md5=yes
  register: after

- debug: msg='report this task as "changed" if file changed'
  changed_when: "'{{before.stat.md5}}' != '{{after.stat.md5}}'"

- debug: msg='execute this task if file changed'
  when: "'{{before.stat.md5}}' != '{{after.stat.md5}}'"

If what you really want is to report the task 'write account.ring.gz file' as changed or not changed based on outcome of swift-ring-builder then you have to run a mini shell script. Something like this (not tested):

- name: write account.ring.gz file
  shell: bfr=`md5sum account.ring.gz`; swift-ring-builder account.builder write_ring; aftr=`md5sum account.ring.gz`; test $bfr -eq $aftr
    chdir=/etc/swift

or if I remember the md5sum options correctly:

- name: write account.ring.gz file
  shell: echo `md5sum account.ring.gz` account.ring.gz > /tmp/ff; swift-ring-builder account.builder write_ring; md5sum -c /tmp/ff
    chdir=/etc/swift

Upvotes: 11

Related Questions