Ansible: Check If File Exists

To check whether the destination file exists and then run tasks based on its status, we can use the Ansible’s stat module (or win_stat for Windows targets).

With this module we can identify not only whether the destination path exists or not but also if it is a regular file, a directory or a symbolic link.

Cool Tip: Enable DEBUG mode and increase VERBOSITY in Ansible! Read more →

Check If File Exists

To check if the destination path actually exists or not, use the stat.exists:

tasks:
  - name: "Check if path exists"
    stat:
      path: "/path/to/something"
    register: result
  
  - name: "Do something if path exists"
    command: ...
    when: result.stat.exists

  - name: "Do something else if path doesn't exist"
    command: ...
    when: not result.stat.exists

To check if the destination path is a regular file, use the stat.isreg:

tasks:
  - name: "Check if file exists"
    stat:
      path: "/path/to/something"
    register: result
  
  - name: "Do something if file exists"
    command: ...
    when: (result.stat.isreg is defined) and (result.stat.isreg)

  - name: "Do something else if file doesn't exist"
    command: ...
    when: (result.stat.isreg is undefined) or (not result.stat.isreg)

To check if the directory file exists, use the stat.isdir:

tasks:
  - name: "Check if directory exists"
    stat:
      path: "/path/to/something"
    register: result
  
  - name: "Do something if directory exists"
    command: ...
    when: (result.stat.isdir is defined) and (result.stat.isdir)

  - name: "Do something else if directory doesn't exist"
    command: ...
    when: (result.stat.isdir is undefined) or (not result.stat.isdir)

To check if the symbolic link exists, use the stat.islnk:

tasks:
  - name: "Check if symlink exists"
    stat:
      path: "/path/to/something"
    register: result
  
  - name: "Do something if symlink exists"
    command: ...
    when: (result.stat.islnk is defined) and (result.stat.islnk)

  - name: "Do something else if symlink doesn't exist"
    command: ...
    when: (result.stat.islnk is undefined) or (not result.stat.islnk)

Leave a Reply