How To Manage Files In Ansible: The Ultimate And Easy Guide For Beginners

Manage files in Ansible

In this guide, we will show you how to manage files on remote servers efficiently Ansible built-in modules to manage files on remote machines. Key Modules for File Management are copyfetchfiletemplate, and synchronize. These modules allow users to push files, pull files, manage file properties (like permissions and ownership), and synchronize directories.

Table of Contents

Objectives:

After completing this section, you should be able to Manage Files (create, install, edit, and remove files) on managed hosts, and manage permissions, ownership, SELinux context, and other characteristics of those files.

What is Files Module in Ansible? 

The Files modules library includes modules allowing you to accomplish most tasks related to Linux file management, such as creating, copying, editing, and modifying permissions and other attributes of files. The following table provides a list of frequently used file management modules:

Commonly Used Files Modules

MODULE NAME MODULE DESCRIPTION
blockinfile Insert, update, or remove a block of multiline text surrounded by customizable marker lines.
copy Copy a file from the local or remote machine to a location on a managed host. Similar to the file module, the copy module can also set file attributes, including SELinux context.
fetch This module works like the copy module, but in reverse. This module is used for fetching files from remote machines to the control node and storing them in a file tree, organized by host name.
file Set attributes such as permissions, ownership, SELinux contexts, and time stamps of regular files, symlinks, hard links, and directories. This module can also create or remove regular files, symlinks, hard links, and directories. A number of other file-related modules support the same options to set attributes as the file module, including the copy module.
lineinfile Ensure that a particular line is in a file, or replace an existing line using a back-reference regular expression. This module is primarily useful when you want to change a single line in a file.
stat Retrieve status information for a file, similar to the Linux stat command.
synchronize A wrapper around the rsync command to make common tasks quick and easy. The synchronize module is not intended to provide access to the full power of the rsync command, but does make the most common invocations easier to implement. You may still need to call the rsync command directly via the run module depending on your use case.

How To Automate Linux File Management Tasks With Files Modules ? 

Creating, copying, editing, and removing files on managed hosts are common tasks that you can implement using modules from the Files modules library. The following examples show ways that you can use these modules to automate common file management tasks.

Ensuring a File Exists on Managed Hosts

Use the file module to touch a file on managed hosts. This works like the touch command, creating an empty file if it does not exist, and updating its modification time if it does exist. In this example, in addition to touching the file, Ansible ensures that the owning user, group, and permissions of the file are set to specific values.

tasks:

name:Touch a file on remote Machine

file:

path: path/to/file

owner: devops

group: devops

mode: 0640

     state: touch

Modifying File Attributes:

You can use the file module to manage files to ensure that a new or existing file has the correct permissions or SELinux type as well.

For example, the following file has retained the default SELinux context relative to a user’s home directory, which is not the desired context.

$ ls -Z samba_file
-rw-r--r-- owner group unconfined_u:object_r:user_home_t:s0 samba_file

The following task ensures that the SELinux context type attribute of the samba_file file is the desired samba_share_t type. This behavior is similar to the Linux chcon command.

- name: SELinux type is set to samba_share_t
file:
path: /path/to/samba_file
setype: samba_share_t

Example outcome:

$ ls -Z samba_file
-rw-r--r-- owner group unconfined_u:object_r:samba_share_t:s0 samba_file

How to Make SELinux File Context Changes Persistent?

The file module acts like chcon when setting file contexts. Changes made with that module could be unexpectedly undone by running restorecon. After using  file to set the context, you can use sefcontext from the collection of System modules to update the SELinux policy like semanage fcontext.

name: Using the file module to ensure SELinux file context

  hosts: rhel_hosts

  tasks:

  name: SELinux file context is set to persistent

    sefcontext:

     target: /home/devops/users.txt

     setype: samba_share_t

     state: presen

Example outcome:

$ ls -Z samba_file
-rw-r--r-- owner group unconfined_u:object_r:samba_share_t:s0 samba_file

How To Copy and Edit Files on Managed Hosts To Manage Files?

The copy module is use to copy a file the control node to selected managed hosts. By default this module assumes that force: yes is set. That forces the module to overwrite the remote file if it exists but contains different contents from the file being copied. If force: no is set, then it only copies the file to the managed host if it does not already exist.

The following is the example for how to Copy a file to Managed Hosts and set attributes:

name: Using the copy module

  hosts: rhel_hosts

  tasks:

  name: Copy a file to managed hosts and set attributes

    copy:

     src: files/user.txt

     dest: /home/devops/users.txt

     owner: devops

     group: devops

     mode: u+rw,g-wx,o-rwx

     setype: samba_share_t

How To retrieve files from managed hosts?

You can also manage files in reverse by fetching them from the node to the control machine. To retrieve files from managed hosts use the fetch module. This could be used to retrieve a file such as an SSH public key from a reference system before distributing it to other managed hosts.

- name: Retrieve SSH key from reference host
fetch:
src: "/home/{{ user }}/.ssh/id_rsa.pub
dest: "files/keys/{{ user }}.pub"

What is lineinfile Module ?

lineinfile is an Ansible module used to ensure a single line of text is present, absent, or modified in a file.

It is commonly used for:

  • Editing configuration files

  • Adding environment variables

  • Enforcing security or system settings

  • Making safe, repeatable (idempotent) file changes

Example of lineinfile module:

name: Add text to an existing file

  hosts: rhel_hosts

  tasks:

  – name: Add a single line of text to a file

    lineinfile:

     path: /home/devops/users.txt

     line: “This line was added by the lineinfile module.”

     state: present

 What is blockinfile Module?

blockinfile is an Ansible module used to manage a group (block) of lines together inside a file.
Instead of editing one line (like lineinfile), it inserts, updates, or removes multiple lines as a single unit.

When using the blockinfile module, commented block markers are inserted at the beginning and end of the block to ensure idempotency.

# BEGIN ANSIBLE MANAGED BLOCK
First line in the additional block of text
Second line in the additional block of text
# END ANSIBLE MANAGED BLOCK

You can use the marker parameter to the module to help ensure that the right comment character or text is being used for the file in question.

The following is the Example of blockinfile

 

name: Add block to existing file

  hosts: rhel_hosts

  tasks:

  name: Add a block of text to an existing file

    blockinfile:

      path: /home/devops/users.txt

      block: |

        This block of text consists of two lines.

        They have been added by the blockinfile module.

      state: present

How to Remove a file from Managed Host?

A basic example to remove a file from managed hosts is to use the file module with the state: absent parameter. 

– name: Make sure a file does not exist on managed hosts

file:

dest: /path/to/file

state: absent

Retrieving the Status of a File on Managed Hosts

The stat module retrieves facts for a file, similar to the Linux stat command. Parameters

provide the functionality to retrieve file attributes, determine the checksum of a file, and more.

The stat module returns a hash dictionary of values containing the file status data, which allows you to refer to individual pieces of information using separate variables.

 

The following example registers the results of a stat module and then prints the MD5 checksum of the file that it checked. (The more modern SHA256 algorithm is also available; MD5 is being used here for easier legibility.)

- name: Verify the checksum of a file
stat:
path: /path/to/file
checksum_algorithm: md5
register: result
- debug
msg: "The checksum of the file is {{ result.stat.checksum }}"

The outcome should be similar to the following:

TASK [Get md5 checksum of a file] *****************************************
ok: [hostname]
TASK [debug] **************************************************************
ok: [hostname] => {
"msg": "The checksum of the file is 5f76590425303022e933c43a7f2092a3"
}

Information about the values returned by the stat module , you can register a variable and display its contents to see what is available:

- name: Examine all stat output of /etc/passwd
hosts: localhost
tasks:
- name: stat /etc/passwd
stat:
path: /etc/passwd
register: results - name: Display stat results debug:
var: result

How To Synchronizing Files Between the Control Node and Managed ?

The synchronize module is a wrapper around the rsync tool, which simplifies common file management tasks in your playbooks. The rsync tool must be installed on both the local and remote host. By default, when using the synchronize module, the “localhost” is the host that the synchronize task originates on (usually the control node), and the “destination host” is the host that synchronize connects to. The following example synchronizes a file located in the Ansible working directory to the managed hosts:

- name: synchronize local file to remote files
synchronize:
src: file
dest: /path/to/file

There are many ways to use the synchronize module and its many parameters, including synchronizing directories. Run the ansible-doc synchronize command for additional parameters and playbook examples.

Conclusion Of How to Manage Files:

Ansible makes it easy to manage files on remote machines by using simple, reliable, and idempotent modules. With tools like file, copy, and template, administrators can automate file operations, maintain consistency, and reduce manual work across multiple systems. This approach helps ensure efficient configuration management and scalable infrastructure automation.

To know more aboute how to Manage Files on Manage hosts in ansible please visit Ansible public docs page How To Manage Files On Remote Machines

To know more about Ansible you can also visit my website To Know about Ansible To

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top