The Ansible file module manages files and file properties on Linux hosts. You can use it to create, delete, and modify files, as well as set permissions– it even works with symlinks. This module is also regularly used in combination with modules like Ansible’s copy and template to transfer files from a local host (or a code repository) to a remote host. For example, you can use the file module to create a new directory, then use the copy module to copy a file to that new directory, and finally set the permissions on the file so that it is readable/writable/executable by a specific user. (The equivalent Ansible module for Windows hosts is win_file.)
The Ansible file module can be helpful in a variety of scenarios. Perhaps you want to automate the deployment of a web app– in this case, you might use the file module to create the necessary directory structure and file permissions on the host, and then copy the various files for your web app to those directories.
To use the Ansible file module in a playbook, you first need to specify the module name and the path to the file/directory that you want to manage. For example, to create a new directory on a host:
file-example-simple.yml
---
- name: Ansible file module example
hosts: all
vars:
mydir: "/tmp/example_directory"
tasks:
- name: Ensure that a directory exists
ansible.builtin.file:
path: "{{ mydir }}"
state: directory
In the above example, the path parameter specifies the variable “mydir”, which has the location of the directory; and the state parameter is set to directory, which tells Ansible to ensure that the directory exists (and to create this directory for you if it doesn’t already exist).
Commonly, you will also use the the owner and group parameters to ensure the ownership of the file/directory, and the mode parameter to ensure the permissions are set correctly rather than inheriting them from the parent directory:
file-example-with-permissions.yml
---
- name: Ansible file module example
hosts: all
vars:
mydir: "/tmp/example_directory"
tasks:
- name: Ensure that a directory exists
ansible.builtin.file:
path: "{{ mydir }}"
state: directory
owner: ec2-user
group: ec2-user
mode: 0644
In summary, the Ansible file module allows you to manage files and directories on remote Linux hosts. It can be used to create, delete, and modify files, as well as set their permissions, and in Level Up’s opinion, it is one of the first ten Ansible modules you should know.