Last Updated on 2 days by Sachin G

Ansible is widely known for simplifying automation across infrastructure, and one of its most practical features is its ability to handle file operations. It simplifies remote file management through modules like ansible.builtin.copy. This article explores how to use the Ansible copy module to copy files and directories, manage permissions, use variables, and more, all through real-world, idempotent automation.

Installation of Ansible Follow steps Here

    1. What Is the #about-copy-moduleAnsible Copy Module?

    2. Quick ad-hoc command Syntax to execute ansible copy module

    3. Ansible copy directory from local to remote

    1. Copy the directory’s content recursively with an example
    2. Copy the directory with its content recursive with the example

    4. Copy a file to managed hosts and Set Attributes

    What Is the Ansible Copy Module?

    The ansible.builtin.copy The module allows users to perform file transfer with Ansible, enabling them to copy files using Ansible from a local to remote machine or across multiple servers. This is especially useful for Ansible configuration management and handling remote file management efficiently.

    The copy module copies files and directories from one location to managed host locations. it is similar to the file module. The copy can also set permissions and other attributes like ownership, group ownership, links, etc. If you would like to copy files from a remote location to the local system, then you will use the fetch module instead of the copy module. Unlike the synchronize Module (which uses rsync), the copy module is file-based and ideal for simpler tasks such as copying a single file, recursive directory copy, or applying inline content creation.

    Now, let us delve into several anticipated examples pertinent to the copy module. First, we will outline the syntax for both ad-hoc commands and playbook examples. These demonstrations will illustrate the process of copying designated content strings into a ‘test’ file within the ‘opt’ directory. Subsequently, we will proceed to validate the functionality by executing a test scenario involving the transfer of the file to the remote host.

    The best resource to read about any Ansible is ansible documentation, where you list all modules through the ansible-doc -l or if you are using the latest ansible automation platform then ansible-navigator doc -l. you can use a small module name copy instead of using with collection name ansible. builtin but it is recommended to use a fully qualified collection name to link with the module documentation and avoid conflict with other collections. You can read about copy through the below command.

    # ansible-doc ansible.builtin.copy 
    # ansible-navigator doc ansible.builtin.copy 

    You can learn more from the official website Ansible Doc

    How Ansible Handles File Transfer

    With the Ansible copy file to remote capability, the module supports key parameters like:

    • src and dest – define source and destination paths
    • mode, owner, group – manage secure permission settings
    • force, backup, remote_src – control behavior for existing files
    • content – allows for inline content instead of using a source file
    • directory_mode – handles recursive Ansible copy directory tasks

    Quick ad-hoc command Syntax to execute ansible copy module

    Ad-hoc command syntax with ansible.builtin.copy :

    # ansible all -m ansible.builtin.copy  -a 'content="Welcome to Tech Transit \n" dest=/opt/testfile '

    Using the ansible ad-hoc command ansible.builtin.copy create a test file inside the /opt directory and add the content string “Welcome to Tech Transit \n”.

    Output:


    srv1.techtransit.org | CHANGED => {
    "ansible_facts": {
    "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "checksum": "8bbb8b62fd12b14f0ee73a813e50b348f25226a3",
    "dest": "/opt/testfile",
    "gid": 0,
    "group": "root",
    "md5sum": "488908a815822c1fee0df0fbe81334c3",
    "mode": "0644",
    "owner": "root",
    "secontext": "system_u:object_r:usr_t:s0",
    "size": 25,
    "src": "/home/techtransit/.ansible/tmp/ansible-tmp-1663502937.4805746-1244-152772706161681/source",
    "state": "file",
    "uid": 0
    }

    The value in “changed”: true, which means the file in opt is if not created then it will create and add text provided through command.

    Copy directories – Local to Remote


    Copying directories recursively content with an example

     cat directorycontent.yml 
    ---
    - name: Copy the directory’s content recursively with an example  
      hosts: all
      tasks:
        - name: Copy  techdir content in /srv/techtransit to remote host
          ansible.builin.copy:
            src:  /home/techtransit/copytest/techdir/
            dest: /srv/techtransit 

    The above playbook is an example of copy-only content or ansible copy all files / multiple files in directory of techdir directory, not the directory because of trailing /, when we implement trailing slash / then only files will copy. This is great for directory synchronization without needing rsync or the synchronize module.

    ansible.builtin.copy

    Copy the directory and its content recursive with the example :


    Now, the directory and content both will be copied to the remote server.

    Below is the playbook to copy a directory to the remote server.

     ---
    - name: Copy the directory’s content recursively with an example  
      hosts: all
      tasks:
        - name: Copy  techdir content in /srv/techtransit to remote host
          ansible.builtin.copy:
            src:  /home/techtransit/copytest/techdir
            dest: /srv/techtransit

    Now trailing slash has been remote from the old example. Now it should copy the directory to /srv/techtransit .

    Copy a file to managed hosts and Set Attributes

    Below is the playbook sample, which copies the local files to the remote-managed host.

    ---
    - name: Copy file without forcefully
      hosts: all
      tasks:
        - name: Copy  srctest.txt as srcdest.txt in the /opt to remote host
          ansible.builtin.copy:
            src:  /home/techtransit/copytest/srctest.txt
            dest: /opt/srcdest.txt
            force: no 

    We set no force argument, So this will not copy if the file will already exist. Now above playbook will copy the srctest.txt file from the/home/techtransit location and copy it to all managed hosts into /opt destination with the name srcdest.txt.

    The Ansible Copy Module simplifies the task of replicating files and directories across diverse infrastructure environments.

    Advanced Use Cases: Variables, Templates & Conditions

    Ansible supports variable-driven paths, making it easy to use dynamic destinations:

    - name: Copy with variable path
      ansible.builtin.copy:
        src: ./file.conf
        dest: "/etc/{{ app_name }}/file.conf"
    

    For conditional file transfer, you can use when: to control logic:

    - name: Conditionally copy
      ansible.builtin.copy:
        src: file.txt
        dest: /tmp/file.txt
      when: ansible_os_family == "Debian"

    While the template vs copy comparison depends on your use case, use the Ansible template module if the file needs Jinja2 variable processing.