Ansible When File Exists

Ansible When File Exists

--- 
- hosts: localhost 
  gather_facts: no 
  tasks:
  - stat:
      path: /project/decodingdevops.txt
    register: result

  - commannd: cp /project/decodingdevops.txt /project/decodingdevops.backup
    when: result.stat.exists

With ansible, to verify is the file existed or not,  we use ansible stat module with when condition. Stat module is similar to the linux/unix ‘stat’ command. We are storing the result of stat module in result variable. In the second task if the file is existed then we are executing copy command. We can use any module in the place of command module depends on our requirement.

Ansible When File Does Not Exist

--- 
- hosts: localhost 
  gather_facts: no 
  tasks:
  - stat:
      path: /project/decodingdevops.txt
    register: result

  - commannd: touch /project/decodingdevops.txt
    when: result.stat.exists == false

In the second task if the file is not existed, then we are executing command module to create new file. Here also we can use any module in the place of command module depends on our requirement.

Leave a Reply

Your email address will not be published. Required fields are marked *