Using Ansible: Wait and Recover SSH Service after Restart

Abstract: Resolve Ansible connection drops after SSH restart by using the wait_for module to ensure the service is ready before continuing.

Created: 2026-09-06 by
When an Ansible playbook restarts the SSH daemon on a managed node, the connection often drops before subsequent tasks can execute. This article explains how to use the wait_for module to pause execution until the service is fully operational again, ensuring reliable automation without manual intervention or connection timeouts.

The Challenge of Service Restart in Automation

Restarting critical network services like SSH presents a unique challenge for configuration management tools. When the service or systemd module issues a restart command, the process terminates and then initializes a new instance. During this brief window, the listening port is closed, causing the active SSH session used by Ansible to fail immediately. If the next task depends on that same connection, the entire play fails with a "Broken pipe" or "Connection refused" error. This issue is particularly acute when managing remote infrastructure where physical access is unavailable. Unlike local scripts that might sleep for a few seconds, Ansible requires a programmatic way to detect readiness. Relying on static delays like sleep is unreliable because system load varies, and the service might take longer to start under heavy disk I/O or memory pressure. Therefore, a dynamic check is necessary to ensure the service is actually accepting connections before proceeding.

Using the Wait For Module

The most robust solution is the wait_for module, which allows you to wait for a condition to be met before continuing. Specifically, you want to wait for the SSH port (default 22) to become available. This module polls the target host at regular intervals until the specified condition is satisfied or a timeout occurs. Here is a standard pattern for handling this scenario:
- name: Restart SSH service
  ansible.builtin.service:
    name: sshd
    state: restarted

- name: Wait for SSH to come back online
  ansible.builtin.wait_for:
    host: "{{ inventory_hostname }}"
    port: 22
    delay: 5
    timeout: 300
    state: started
In this example, the first task restarts the service. The second task instructs Ansible to connect to {{ inventory_hostname }} on port 22. It waits up to 300 seconds (5 minutes), checking every few seconds (default interval). The delay parameter ensures Ansible waits five seconds after the restart command before starting the poll, giving the OS time to begin the initialization process.

Understanding Key Parameters

The host parameter should usually be set to {{ inventory_hostname }} or {{ ansible_host }}. Using 127.0.0.1 will cause the module to check the *control* node's SSH service, not the target node's, leading to false positives if your control node has SSH running. Always verify the target address. The timeout value must be generous enough to account for slow boot times but short enough to fail fast if the service crashes entirely. A timeout of 300 seconds is generally safe for most Linux distributions. If you are restarting multiple nodes in parallel, consider reducing this slightly to avoid long hangs across the whole fleet.

Handling Connection Recovery Failures

Even with wait_for, there is a race condition between the drop of the current connection and the establishment of the new one. In some cases, Ansible may lose the connection so quickly that it cannot even initiate the wait_for task properly. To mitigate this, you can add a small initial sleep or rely on the delay parameter effectively. If the service fails to start within the timeout, Ansible will raise a fatal error. You can handle this gracefully by wrapping the recovery steps in a block with a rescue section. This allows you to log the failure or attempt a fallback strategy, such as rebooting the machine via IPMI or cloud provider APIs if SSH remains unreachable. For more complex networking scenarios, such as using jump hosts, refer to our guide on Automating a menu presented by a remote SSH jump server. This context highlights additional complexity when managing connectivity through intermediate hops.

Optimizing for Parallel Execution

When restarting SSH on hundreds of servers simultaneously, the collective load on the network and the Ansible controller can be significant. Ensure that your forks setting in ansible.cfg is appropriate. If you are using connection pooling, note that restarting SSH breaks existing persistent connections. You may need to clear the cache or expect Ansible to re-establish them during the next task. Additionally, consider using the async and poll parameters for the restart task itself if you want to fire-and-forget the restart command while waiting for health checks elsewhere. However, for most single-node operations, the sequential approach shown above is clearer and easier to debug.

Alternative Approaches and Considerations

Some administrators prefer using the uri module to hit an HTTP endpoint instead of waiting for a TCP port. This is only viable if you have a web server or health check API running alongside SSH. For pure SSH recovery, TCP port checking via wait_for is the standard and most reliable method. Another consideration is the security implications of restarting SSH. Ensure that your firewall rules allow the incoming connection from the Ansible controller during the restart window. If you are using strict iptables or firewalld rules, they must not block the port during the service transition. For related automation challenges, see Can Ansible Reuse SSH Connection for Rsync? to understand how connection persistence affects other file transfer operations after a service restart.

Frequently Asked Questions

Why does my Ansible playbook fail immediately after restarting SSH?

The failure occurs because the active SSH session is terminated when the service stops. Since Ansible relies on that specific socket for communication, any subsequent task sent over that channel results in a broken pipe error before the new service instance is ready.

Can I use the sleep module instead of wait_for?

While you can use a simple sleep command, it is not recommended. Sleep introduces a fixed delay regardless of system load, meaning your playbook runs slower than necessary on fast systems or fails on slow ones. The wait_for module dynamically checks for readiness, providing a more efficient and reliable recovery mechanism.

What happens if the SSH service fails to start within the timeout?

If the service does not respond within the specified timeout period, the wait_for module raises a fatal error, terminating the playbook run. This prevents silent failures where subsequent tasks execute against a non-functional system, allowing you to investigate the root cause via logs or alternative access methods.

Do I need to specify the host parameter in wait_for?

Yes, you must explicitly set the host parameter to the target node's IP or hostname. If omitted, Ansible defaults to localhost, which checks the control node's status rather than the managed node's, leading to incorrect health checks and potential false positives.

How does this affect connection caching in Ansible?

Restarting SSH invalidates any existing persistent connections stored in the control node's connection cache. Ansible will need to establish a new SSH handshake once the service is back online. This adds a slight overhead to the first task executed after recovery compared to tasks using cached connections.

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