Can Ansible Reuse SSH Connection for Rsync?

Abstract: Configure SSH connection sharing in Ansible to reuse existing connections for rsync, reducing latency and overhead during file transfers.

Created: 2026-10-13 by
Yes, Ansible can reuse existing SSH connections for rsync operations by configuring the connection plugin and leveraging the ControlMaster feature. This approach significantly reduces latency and overhead when transferring multiple files or directories to remote hosts, as it avoids the cost of establishing new TCP and authentication handshakes for every single transfer.

Understanding Ansible Connection Plugins

Ansible manages how it communicates with remote hosts through connection plugins. The default is usually ssh, but you can optimize this behavior using the smart connection type or by explicitly setting parameters in your inventory or playbook. To enable connection sharing, you must ensure that the underlying SSH client supports multiplexing via the -M (master) and -S (socket) flags.

When Ansible initiates a task, it checks if a persistent connection already exists. If one does, it attaches to the existing socket instead of opening a new port. This is crucial for performance-intensive tasks like large directory transfers where the setup time for SSH negotiation becomes a bottleneck relative to the data transfer speed.

Configuring Persistent Connections

To make Ansible reuse SSH connections, you need to configure the control master settings. This can be done globally in ansible.cfg or locally within a playbook. The key configuration items are control_path, control_master, and controlPersist.

  • control_master: Set this to auto or yes. auto allows Ansible to decide based on other factors, while yes forces master mode.
  • control_path: Define a path for the socket file. A common pattern is /tmp/ansible-ssh-%h-%p-%r, which ensures uniqueness per host, port, and user.
  • controlPersist: Specify how long the connection should remain open after the last client disconnects. Setting this to 60s or higher keeps the channel warm for subsequent tasks.

Example configuration in ansible.cfg:

[ssh_connection]
control_path = /tmp/ansible-ssh-%%h-%%p-%%r
control_master = auto
controlPersist = 60s

This setup ensures that once the first task establishes an SSH session, all subsequent tasks within that run will piggyback on the same connection. This is particularly effective when combined with the synchronize module, which is Ansible's wrapper around rsync.

Using the Synchronize Module Efficiently

The synchronize module is the standard way to perform rsync operations in Ansible. It abstracts the complexity of rsync command-line arguments while allowing you to leverage the underlying SSH connection reuse. When you use the synchronize module, Ansible invokes rsync on the controller and pushes/pulls files to/from the target.

Because the synchronize module runs as a task, it benefits from the global SSH connection settings. However, for maximum efficiency, you can also pass extra arguments directly to rsync via the rsync_opts parameter. While these options don't change the SSH layer, they optimize the data transfer itself.

Consider the following playbook snippet:

- name: Sync directory using reused SSH connection
  ansible.builtin.synchronize:
    src: ./local/dir/
    dest: /remote/path/
    recursive: yes
    compress: yes
    delete: yes

In this scenario, if you have previously configured persistent SSH connections, the synchronize module will utilize the existing master socket. This means the initial handshake overhead is paid only once, regardless of how many files are transferred.

Handling Multiple Hosts

If you are syncing to multiple remote hosts, each host requires its own SSH master socket. The control_path template must include variables like %h (hostname) to prevent socket collisions. Without this, Ansible might try to route traffic for Host B through Host A's socket, leading to authentication failures or data corruption.

Ensure your inventory or group variables reflect distinct hostnames. If you are using aliases, resolve them to canonical names before generating the socket path. This detail is often overlooked but critical for stable multi-host deployments.

Debugging Connection Issues

Sometimes, connection reuse fails due to permission issues or stale sockets. If you encounter errors like "Permission denied" or "Connection reset," check the permissions of the directory specified in control_path. The user running Ansible must have write access to this directory.

You can also manually inspect the socket files to see if they are active. Using ls -l /tmp/ansible-ssh-* will show you the current master sockets. If a socket appears old but the connection is dead, you may need to clear the cache or adjust the controlPersist value.

For deeper insights, run Ansible with the -vvv flag. This verbose output will show exactly how the SSH connection is being established and whether it is attaching to an existing master or creating a new one. Look for lines containing "ControlMaster" and "ControlPath" in the debug logs.

Alternative Approaches

If you find that the synchronize module is too rigid for your needs, you can use the shell or command modules to invoke rsync directly. However, this bypasses some of Ansible's built-in optimizations and error handling. You would need to manually manage the SSH connection state, which is generally not recommended unless you have very specific requirements.

Another alternative is to use the copy module for smaller files, as it uses a different transport mechanism that may not benefit as much from SSH multiplexing. For large-scale directory syncs, sticking with synchronize and proper SSH configuration remains the best practice.

For more advanced scenarios involving network storage, you might explore mirroring strategies. See Using rsync to mirror the contents of a directory on a NAS for techniques applicable to static infrastructure.

Frequently Asked Questions

Does SSH connection reuse work with password authentication?

No, SSH multiplexing typically requires public key authentication or cached credentials. Password prompts break the non-interactive nature of the master socket. Ensure you have set up SSH keys for seamless automation.

What happens if the SSH connection drops during a sync?

Ansible will detect the broken pipe and attempt to reconnect. With controlPersist set, the master socket may remain open briefly, but if the network fails completely, a new connection will be established for the next task. Always implement retry logic for critical syncs.

Can I limit the number of concurrent SSH connections?

Yes, by using forks in your playbook or ansible.cfg. Reducing forks limits the number of simultaneous SSH sessions, which can help avoid overwhelming the server's connection table. This works in tandem with connection reuse to optimize resource usage.

How do I clean up stale SSH sockets?

You can manually delete files in the control_path directory. Alternatively, set a shorter controlPersist value so that sockets expire automatically. Regular cleanup prevents disk space issues and ensures fresh connections when needed.

Is rsync over SSH slower than direct NFS mounts?

Generally, no. Modern SSH compression and efficient packet handling make rsync over SSH highly performant. While NFS might offer lower latency for small files, rsync's delta-transfer algorithm saves bandwidth for large datasets. Choose based on your network topology and security requirements.

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