Ansible

Ansible File Module Tutorial

Ansible is an incredible automation utility that comes packed with features and tools to manage remote hosts. It works by implementing modules to perform specific tasks and operations.

One practical module in Ansible is the file module. This module is responsible for performing tasks such as creating files and directories, deleting files and directories, creating soft and hard symbolic links, adding and modifying file and directory permissions, and more.

This guide will walk you through how to work with the Ansible file module. We will illustrate this using a collection of examples and playbooks.

NOTE: Ensure you have access to your remote hosts specified in Ansible’s inventory file.

How The Ansible File Module Works

The Ansible.builtin.file module is in the default ansible installation as part of ansible-core. Ansible recommends referring to the module using the “Fully Qualified Name” instead of the short module name to avoid conflicts with modules of similar names.

The file module contains a collection of pre-defined parameters for file management. We use these parameters to configure the actions performed on the remote host.

The following are important parameters you can use:

  1. Owner – Username of the user who’ll own the created file and directory
  2. Path – Path to the file or directory to manage
  3. Mode – Permission mode to set on the specified file or directory. Use octal notation inside a pair of single quotes.
  4. Group – Sets the group ownership for a file or directory
  5. Force – A Boolean value used to force the creation of symlinks if the source file is not currently available (but added later) or the destination symlink already exists.
  6. Follow – If filesystem links exist, follow them.
  7. Attributes – Sets attributes for the specified file or directory. Similar to the default chattr utility in Linux
  8. State – Defines the context for a file’s creation. Accepted options include:
    1. Touch – Create an empty file
    2. Directory – Create a directory
    3. Hard – Create a hard link
    4. Link – Create a soft link
    5. Absent – Delete files and directory recursively and unlink links

Check the ansible file module docs for other pre-defined parameters.

The best way to learn how to work with the Ansible file module is by examples.

Ansible File Module: Practical Examples

NOTE: This guide assumes you have an Ansible control node and your target hosts added to your inventory file.

How to create an empty file

To create an empty file using the ansible file module, we set the state to touch as illustrated in the playbook.

---
- hosts
: all
  tasks
:
  - name
: create empty file
    file
:
      path
: $HOME/touch_file
      state
: touch

The above playbook contains basic ansible configuration:

  1. host – Sets the remote target hosts to run the playbook. You can define a group of remote hosts or a single host.
  2. tasks – Tells Ansible to run the specified task on the remote host.
  3. name – Specifies the task’s name to run
  4. file – Calls the Ansible file module
  5. path – Defines a path on the remote machine where the file is created.
  6. state – Create an empty file using touch.

Save the playbook and execute it on the remote hosts:

ansible-playbook emptyfile.yml

How to create multiple files

Ansible allows you to create multiple files in a single task. Below is an example playbook:

---
- hosts
: all
  tasks
:
  - name
: create multiple files
    file
:
      path
: $HOME/{{ item }}
      state
: touch
    with_items
:
   - file1.c
    - header.h
    - file2.py
    - file3.txt
    - file4.rb

In the playbook, we utilize two ansible entries:

  1. {{ item }} – Tells Ansible to create a unique path for the specified files.
  2. with_item – Creates a list of files to create on the remote host. You can add as many files and extensions as you see fit.

Run the ansible-playbook to create specified multiple files:

ansible-playbook multiplefiles.yml

How to create a file with content

In the examples above, we create empty files using the touch command. To create a file with contents, we can use the copy module and set the content parameter to the file’s contents.

Below is an example playbook:

---
- hosts
: all
  tasks
:
  - name
: create file with contents
    copy
:
      dest
: $HOME/hello.cpp
      content
: |
       #include
        using namespace std
        int main () {
          cout << "hello world" << endl;

          return 0;
        }

The modules and parameters in the above playbook are:

  1. copy – Involves the ansible copy module.
  2. dest – The destination path for your file
  3. content – The content to add to your file. Each line is added to a new line.

Run the playbook:

ansible-playbook withcontent.yml

How to create a directory

The playbook used to create a directory using the Ansible file module is similar to creating an empty file. However, as shown below, we set the state to “directory” instead of “file”:

---
- hosts
: all
  tasks
:
  - name
: createadirectory
    file
:
      path
: $HOME/ansible-dir
      state
: directory

How to delete a file or symbolic link

Removing files, directories, or symbolic links is very straightforward; all we have to do is to set the state to absent, as shown in the playbook below:

---
- hosts
: all
  tasks
:
  - name
: removefiles
    file
:
      path
: $HOME/ansible-dir
      state
: absent

The playbook will do nothing if the file specified does not exist.

How to change a directory’s permission

We use the playbook’s owner, group, and mode parameters to change a directory’s permission.

The following example will set the specified permissions on the directory.

---
- hosts
: all
  become
: true
  tasks
:
  - name
: modifydirpermissions
    file
:
      path
: /var/log
      state
: directory
      owner
: root
      group
: root
      mode
: 0755

In the example playbook above, we set become: true. This is necessary when setting permissions for other users, except {{ ansible_user }}

  1. Use octal notation to specify permissions, including the leading 0.

Using symbolic mode

Ansible allows you to set the permissions in symbolic mode instead of octal format. The mode below is equivalent to 0777.

---
- hosts
: all
  become
: true
  tasks
:
  - name
: modifydirpermissions in symbolic format
    file
:
      path
: /var/log/
      state
: directory
      mode
: u=rwx,g=rwx,o=rwx

NOTE: Setting 0777 to a directory such as /var/log is not the best practice, and we have used it here for illustration purposes only.

Change directory permissions recursively

If you want to change permissions on a directory recursively, you can use the recurse parameter as shown in the playbook below:

---
- hosts
: all
  become
: true
  tasks
:
  - name
: modifydirpermissionsrecursively
    file
:
      path
: /var/log/
      state
: directory
      owner
: root
      group
: root
      mode
: 0755
      recurse
: true

Setting recurse: true will affect the files inside the specified parent directory.

How to create a symbolic link

Creating a symlink using the Ansible file module is as simple as creating an empty directory. In this case, we set the state to link as shown in the example playbook below:

---
- hosts
: all
- become
: true
  tasks
:
  - name
: createasymlink
    file
:
src
: $HOME/src_file
dest
: /etc/dest_symlink
      state
: link

How to delete a symbolic link

Removing a symlink is similar to removing a regular file.

---
- hosts
: all
- become
: true
  tasks
:
  - name
: removeasymlink
    file
:
      path
: /etc/dest_symlink
      state
: absent

How to modify access time

You can modify the access and modification time using the access_time and modification_time parameters.

Example playbook:

- become: true
  tasks
:
  - name
: modifyaccessandmodifiedtime
    file
:
      path
: /etc/ansible/hosts
      state
: file
access_time
: now
modification_time
: "202110041123.11"

We set the access_time as the current time using the now function.

You can also provide time for access_time and modification_time parameters in the format (as a string):

YYYYmmddHHMM.SS

Conclusion

This guide has helped you understand how to work with the Ansible file module in a playbook.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list