Ansible Playbook: Copy Only Changed or New Files

Abstract: Resolve inefficient file transfers by using Ansible synchronize module to copy only new or changed files and optionally delete stale ones.

Created: 2026-09-24 by
To copy only new or changed files using Ansible, the most reliable method is leveraging the synchronize module, which acts as a wrapper around rsync. This approach ensures that destination files are updated based on modification time and size differences, significantly reducing transfer overhead compared to standard file copying modules. By configuring the delete parameter appropriately, you can also manage stale files on the target host while maintaining synchronization integrity across your infrastructure.

Understanding the Synchronize Module

The synchronize module is designed specifically for efficient file transfers between local and remote hosts, or between two remote hosts. It uses the rsync utility under the hood, which provides a delta-transfer algorithm. This means it only sends the differences in files rather than transferring entire files every time. For large directory trees, this performance gain is substantial. When managing file permissions alongside synchronization, you might need to adjust settings after the copy operation completes, as discussed in our guide on Managing File Permissions in Ansible Playbooks: chmod for Small Directory Trees vs. Large Directory Trees. The primary advantage of using synchronize over the copy or template modules is its ability to handle incremental updates. The copy module will overwrite the destination file if the source content differs, but it does not inherently check for changes in the same efficient manner as rsync. While copy has a checksum option, it calculates the checksum locally before transfer, which can be slow for large files. In contrast, synchronize performs the comparison on the remote side (or via the rsync protocol), minimizing data movement.

Basic Configuration for Incremental Copies

A basic playbook task utilizing the synchronize module requires defining the source and destination paths. The src parameter specifies the location on the controller (or local host), while dest defines the target path on the managed node. By default, synchronize will skip files that have already been copied and have not changed since the last run. Here is a simple example structure:
- name: Sync files to remote server
  ansible.builtin.synchronize:
    src: /path/to/local/files/
    dest: /path/to/remote/files/
    mode: push
In this configuration, the mode: push parameter explicitly indicates that files are being sent from the control node to the target. If omitted, Ansible defaults to pushing files when connecting to a remote host. The module automatically handles the creation of necessary directories if they do not exist, provided the user has appropriate write permissions. It is crucial to ensure that rsync is installed on both the control node and the target hosts. Without rsync, the synchronize module will fail silently or throw an error indicating the command is missing. If you encounter issues with connection stability during these operations, reviewing strategies for SSH reuse can help maintain consistent performance, as outlined in Can Ansible Reuse SSH Connection for Rsync?.

Handling Deletion of Stale Files

One common requirement in synchronization tasks is ensuring that files deleted from the source are also removed from the destination. By default, the synchronize module does not delete files on the destination that no longer exist in the source. To enable this behavior, you must set the delete parameter to true.
- name: Sync files and delete stale ones
  ansible.builtin.synchronize:
    src: /path/to/local/files/
    dest: /path/to/remote/files/
    delete: true
    mode: push
Using delete: true makes the synchronization bidirectional in terms of existence checks, effectively making the destination a mirror of the source. Exercise caution with this setting, as accidental misconfiguration could lead to unintended data loss on the target server. Always verify the paths and ensure that the source directory accurately reflects the desired state of the destination. For scenarios where you want to preserve certain files or directories from deletion, you can use the exclude parameter to specify patterns that should be ignored during the sync process. This allows for more granular control over which files are considered "stale."

Optimizing Performance with Checksums

While synchronize is generally fast, you may occasionally need to force a re-copy even if files appear unchanged. This can be achieved by using the checksum parameter, which forces the module to compare file checksums rather than relying solely on modification times and sizes. This is useful when files have been modified without updating their timestamps, a situation that can occur with certain backup tools or manual edits.
- name: Force sync based on checksum
  ansible.builtin.synchronize:
    src: /path/to/local/files/
    dest: /path/to/remote/files/
    checksum: true
    mode: push
Setting checksum: true ensures that any change in file content triggers a copy, regardless of timestamp. However, this comes at a performance cost, as calculating checksums for large files takes time. Use this option sparingly, primarily for critical configuration files where content integrity is paramount.

Integrating with Variable Management

When scaling these synchronization tasks across multiple environments, managing variables becomes essential. You can define source and destination paths as variables to make your playbooks more flexible. This approach aligns with best practices for combining common and specific variables, as described in Combining Common and Specific Vars in Ansible. By structuring your variables hierarchically, you can easily switch between development, staging, and production targets without modifying the core logic of the synchronize task. This modularity enhances maintainability and reduces the risk of errors when deploying changes across different infrastructure components.

Frequently Asked Questions

Why is my synchronize task failing with 'rsync not found'?

The synchronize module requires the rsync executable to be present on both the control node and the target hosts. Install rsync using your package manager (e.g., apt install rsync or yum install rsync) on all affected machines.

How do I exclude specific files from being synced?

Use the exclude parameter within the synchronize task to specify patterns of files or directories to ignore. For example, exclude: "*.log" will prevent log files from being transferred to the destination.

Can synchronize work between two remote hosts?

Yes, by setting delegate_to to one of the remote hosts, you can initiate a sync between two remote servers. This requires SSH keys to be configured between those hosts so that the delegated host can access the other.

What is the difference between synchronize and copy regarding performance?

Synchronize uses rsync's delta-transfer algorithm, sending only changed parts of files, whereas copy typically transfers the entire file if the content differs. This makes synchronize significantly faster for large files with minor changes.

Does synchronize update file permissions automatically?

No, the synchronize module does not modify file permissions unless explicitly told to via additional parameters like perms. You should follow up with a separate task using the file module to ensure correct ownership and permissions.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More