Mastering File Management with Ansible
Tags: ansible, coding, programming, tutorial
Published: 2024-07-12 03:24:12


## Introduction

This article covers the following tech skills:

![Skills Graph](https://skills-graph.labex.io/ansible-file-module-289654.jpg)

In [this lab](https://labex.io/tutorials/ansible-file-module-289654), you will explore the Ansible File module, which allows you to manage files and directories on remote hosts. The File module provides a wide range of functionalities, such as creating, deleting, modifying permissions, and checking the existence of files and directories.


## Create a File on Remote Host

In this step, you will create a file on a remote host using the Ansible File module.

First, create a new Ansible playbook file called `/home/labex/project/file-module-playbook.yaml` and open it in a text editor.
Add the following content to the playbook file:

```yaml
- hosts: localhost
  tasks:
    - name: Create a file on remote host
      file:
        path: /home/labex/file.txt
        state: touch
```

- `file`: Ansible module to manipulate the file system.
- `path`: Specifies the path to the file, in this case `/home/labex/file.txt`.
- `state`: Specifies the state of the file. Here, `touch` indicates that the file will be created if it does not exist, or updated with access and modification timestamps if it already exists.

The purpose of this playbook is to create a file named `file.txt` on the remote host.

Then, run the playbook using the following command:

```bash
ansible-playbook file-module-playbook.yaml
```

Example output:

```bash
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that
the implicit localhost does not match 'all'

PLAY [localhost] ***************************************************************

TASK [Gathering Facts] *********************************************************
ok: [localhost]

TASK [Create a file on remote host] ********************************************
changed: [localhost]

PLAY RECAP *********************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
```

Finally, verify that the file `file.txt` is created in the specified path on the remote host.

```bash
ll /home/labex/file.txt
```

Example output:

```bash
-rw-rw-r-- 1 labex labex  0 Mar 10 03:12 file.txt
```

You will see the message indicating that `/home/labex/file.txt` was successfully created.


## Manage File Permissions

In this step, you will learn how to manage file permissions on a remote host using the Ansible File module.

First, modify the existing playbook file by removing all content and adding the following content to the playbook file:

```yaml
- hosts: localhost
  tasks:
    - name: Set file permissions
      file:
        path: /home/labex/file.txt
        mode: "0644"
```

- `file`: Ansible module to manipulate the file system.
- `path`: Specifies the path to the file, in this case `/home/labex/file.txt`.
- `mode`: This parameter is used to set the permission mode of the file. Replace `"0644"` with the desired permission mode for the file. Refer to the [chmod](https://en.wikipedia.org/wiki/Chmod) documentation for more information on permission modes.

The purpose of this playbook is to set the permissions of the file `/home/labex/file.txt` to `0644`.

Then, run the playbook using the following command:

```bash
ansible-playbook file-module-playbook.yaml
```

Example output:

```bash
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that
the implicit localhost does not match 'all'

PLAY [localhost] ***************************************************************

TASK [Gathering Facts] *********************************************************
ok: [localhost]

TASK [Set file permissions] ****************************************************
changed: [localhost]

PLAY RECAP *********************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
```

Finally, verify that the file permissions are set as specified on the remote host.

```bash
ll /home/labex/file.txt
```

Example output:

```bash
-rw-r--r-- 1 labex labex 0 Mar 10 03:12 /home/labex/file.txt
```

The `-rw-r--r--` here indicates that the mode of `/home/labex/file.txt` has been successfully set to `0644`.


## Delete a File on Remote Host

In this step, you will learn how to delete a file on a remote host using the Ansible File module.

First, modify the existing playbook file by removing all content and adding the following content to the playbook file:

```yaml
- hosts: localhost
  tasks:
    - name: Delete a file on remote host
      file:
        path: /home/labex/file.txt
        state: absent
```

- `file`: Ansible module to manipulate the file system.
- `path`: Specifies the path to the file to be deleted, i.e. `/home/labex/file.txt`.
- `state`: This parameter indicates that the file should be in the `absent` state. Therefore, the goal of the task is to delete the file at the specified path.

The purpose of this playbook is to delete the file `/home/labex/file.txt` on the remote host.

Then, run the playbook using the following command:

```bash
ansible-playbook file-module-playbook.yaml
```

Example output:

```bash
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that
the implicit localhost does not match 'all'

PLAY [localhost] ***************************************************************

TASK [Gathering Facts] *********************************************************
ok: [localhost]

TASK [Delete a file on remote host] ********************************************
changed: [localhost]

PLAY RECAP *********************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
```

Finally, verify that the file `file.txt` is deleted and no longer exists on the remote host.

```bash
ll /home/labex/file.txt
```

Example output:

```bash
ls: cannot access '/home/labex/file.txt': No such file or directory
```

This message indicates that the `/home/labex/file.txt` file was successfully deleted.


## Check File Existence

In this step, you will learn how to check the existence of a file on a remote host using the Ansible File module.

First, modify the existing playbook file by removing all content and adding the following content to the playbook file:

```yaml
- hosts: localhost
  tasks:
    - name: Check file existence on remote host
      stat:
        path: /home/labex/file.txt
      register: file_info

    - name: Print file existence
      debug:
        msg: "File exists: {{ file_info.stat.exists }}"
```

- `stat`: This is one of Ansible's modules for getting status information about a file or directory.
- `path`: Specifies the path to the file to check, i.e. `/home/labex/file.txt`.
- `register`: Stores the result of the module execution in the variable `file_info` using the register keyword.
- `debug`: This is one of the Ansible modules that prints debugging information.
- `msg`: Use the `debug` module to print a message with information about the existence of a file, which is retrieved via `file_info.stat.exists`.

The purpose of this playbook is to check for the existence of the file `/home/labex/file.txt` on the remote host and print the information to standard output.

Then, run the playbook using the following command:

```bash
ansible-playbook file-module-playbook.yaml
```

Example output:

```bash
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that
the implicit localhost does not match 'all'

PLAY [localhost] ***************************************************************

TASK [Gathering Facts] *********************************************************
ok: [localhost]

TASK [Check file existence on remote host] *************************************
ok: [localhost]

TASK [Print file existence] ****************************************************
ok: [localhost] => {
    "msg": "File exists: False"
}

PLAY RECAP *********************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
```

Finally, observe the output to see if the file `file.txt` exists on the remote host.
`"msg": "File exists: False"` indicates that the `/home/labex/file.txt` file does not exist.


## Summary

Congratulations! You have successfully completed the Ansible File Module lab. You have learned how to create files and directories, manage file permissions, delete files, and check file existence on remote hosts using the File module.

The File module is a powerful tool in Ansible that enables you to perform various file-related operations during automation tasks. You can now confidently use the File module in your Ansible playbooks to manage files and directories efficiently.

Keep exploring the Ansible documentation and other modules to expand your knowledge and improve your automation skills. Happy Ansible-ing!

![MindMap](https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/authcode/?code=NzhlNDRmNDlkNTUzZDE0ODkzNjU0ODUzYzk0MGIwZjBfMTdmMWEwOTU5NjVmZThkZjY3MDYyOGMwYjlhZTAwYjRfSUQ6NzM5MDU4NDg3ODc2NzI3NjAzNF8xNzIwNzU0NjUxOjE3MjA4NDEwNTFfVjM)

---

> 🚀 Practice Now: [Ansible File Module](https://labex.io/tutorials/ansible-file-module-289654)

---

## Want to Learn More?

- 🌳 Learn the latest [Ansible Skill Trees](https://labex.io/skilltrees/ansible)
- 📖 Read More [Ansible Tutorials](https://labex.io/tutorials/category/ansible)
- 💬 Join our [Discord](https://discord.gg/J6k3u69nU6) or tweet us [@WeAreLabEx](https://twitter.com/WeAreLabEx)