How to check if a file exists in Ansible?

E Dine Sh picture E Dine Sh · Feb 26, 2016 · Viewed 215.3k times · Source

I have to check whether a file exists in /etc/. If the file exists then I have to skip the task. Here is the code I am using:

- name: checking the file exists
  command: touch file.txt
  when: $(! -s /etc/file.txt)

Answer

Arbab Nazar picture Arbab Nazar · Feb 28, 2016

You can first check that the destination file exists or not and then make a decision based on the output of its result:

    tasks:
      - name: Check that the somefile.conf exists
        stat:
          path: /etc/file.txt
        register: stat_result

      - name: Create the file, if it doesnt exist already
        file:
          path: /etc/file.txt
          state: touch
        when: not stat_result.stat.exists