Ansible Check If Files or Directories Exist

Ansible stat Module: Ansible Check if File or Directory Exists

When automating tasks with Ansible, you often need to check if a specific file or directory exists on a remote host. This can be useful in scenarios where certain actions are only performed if a particular file or folder is present. In Ansible, this is typically done using the stat module, which gathers information about files or directories.

In this guide, we will explore how to use the Ansible stat module to check if a file or directory exists, along with some practical examples.

Using the stat Module

The stat module in Ansible is used to retrieve information about a file or directory. It provides various attributes like the file size, permissions, and whether the file or directory exists.

The stat module’s basic syntax is:

- name: Check file or directory status
  ansible.builtin.stat:
    path: /path/to/file_or_directory

To determine if the file or directory exists, we use the stat.exists attribute.

Check if a File Exists

In this example, we will check if a specific file exists on the remote host.

---
- name: Check if a file exists
  hosts: all
  tasks:
    - name: Check if the file exists
      ansible.builtin.stat:
        path: /tmp/example.txt
      register: file_status

    - name: Display file existence status
      debug:
        msg: "File exists"
      when: file_status.stat.exists

In this example:

  • stat Module: The stat module checks the status of the file /tmp/example.txt.
  • Register Variable: We store the output of the stat module in a variable called file_status.
  • Conditional Check: Using when: file_status.stat.exists, we display a message if the file exists.

If the file exists, you will see:

TASK [Display file existence status] *******************************************
ok: [target_host] => {
    "msg": "File exists"
}

If the file does not exist, the task is skipped.

skipping: [target_host]

Check if a Directory Exists

Checking for a directory is similar to checking for a file. In this example, we will verify if the /var/log/myapp directory exists.

---
- name: Check if a directory exists
  hosts: all
  tasks:
    - name: Check if the directory exists
      ansible.builtin.stat:
        path: /var/log/myapp
      register: dir_status

    - name: Display directory existence status
      debug:
        msg: "Directory exists"
      when: dir_status.stat.exists

In this example playbook:

  • We use the stat module to check the status of the directory /var/log/myapp.
  • The existence of the directory is determined using dir_status.stat.exists.

If the directory exists, you will see the below output:

TASK [Display directory existence status] **************************************
ok: [target_host] => {
    "msg": "Directory exists"
}

If the directory does not exist, the task is skipped:

skipping: [target_host]

Perform an Action Based on File/Directory Existence

You can perform specific tasks based on whether a file or directory exists. For example, you may want to create a file if it does not exist using the when condition.

---
- name: Create a file if it does not exist
  hosts: all
  tasks:
    - name: Check if the file exists
      ansible.builtin.stat:
        path: /tmp/config.cfg
      register: file_check

    - name: Create the file if it does not exist
      ansible.builtin.file:
        path: /tmp/config.cfg
        state: touch
      when: not file_check.stat.exists

In this example:

  • We check if the file /tmp/config.cfg exists using the stat module.
  • If the file does not exist (not file_check.stat.exists), the file module creates it.

Check File Permissions and Change Them If Not as Expected

In addition to checking for the existence of a file or directory, you may need to verify its permissions and ensure they meet your requirements. Ansible’s stat module can be used to retrieve permission details, and the file module can then be used to correct them if necessary.

In this example, we will check the permissions of a file /tmp/secure_file.txt and ensure that it has 0644 permissions.

---
- name: Check and Correct File Permissions
  hosts: all
  tasks:
    - name: Check the permissions of the file
      ansible.builtin.stat:
        path: /tmp/secure_file.txt
      register: file_permission_check

    - name: Display the current file permissions
      debug:
        msg: "Current permissions are: {{ file_permission_check.stat.mode }}"

    - name: Set correct file permissions if not as expected
      ansible.builtin.file:
        path: /tmp/secure_file.txt
        mode: '0644'
      when: file_permission_check.stat.mode != '0644'

In this example:

  • The stat module retrieves the current permissions of /tmp/secure_file.txt.
  • Using the debug module, we print the current permissions of the file.
  • The file module sets the permissions to 0644 only if they do not match the expected value.

Conclusion

In this article, we explored how to use the Ansible stat module to check if a file or directory exists. This is a common task in many automation scenarios, allowing you to conditionally perform actions based on the presence of files or directories. By using the stat module, you can write more robust and reliable Ansible playbooks.

FAQs

1. How can I create a file if it does not exist in Ansible?

You can use the stat module to check if a file exists and the file module with state: touch to create it if it does not exist.

2. How do I check if a file is a directory in Ansible?

The stat module provides the isdir attribute. If it returns true, the path is a directory. Use this in conditional statements to distinguish between files and directories.

3. Can I check for symbolic links using Ansible's stat module?

Yes, the stat module includes an islnk attribute. If it returns true, the specified path is a symbolic link.

4. How do I change the owner and group of a file in Ansible?

Use the file module with owner and group parameters to update the ownership of a file or directory.

About Hitesh Jethva

I am Hitesh Jethva, Founder and Author at Code2DevOps.com. With over 15 years of experience in DevOps and open source technologies, I am passionate about empowering teams through automation, continuous integration, and scalable solutions.

View all posts by Hitesh Jethva