The play has been running for 6 minutes. Forty hosts finished Gathering Facts, three did not, and the output for those three is the same block of red text:
fatal: [web07]: UNREACHABLE! => {"changed": false,
"msg": "Failed to connect to the host via ssh: ssh: connect to host 10.20.4.17 port 22: Connection timed out",
"unreachable": true}
Someone in the channel suggests raising the timeout. Someone else suggests rerunning with --limit web07. Both might make the error go away for a day. Neither explains why three machines in the same subnet as forty healthy ones cannot be reached.
A better habit is to treat a connection timeout as a network path question first, answer it with the exact SSH command Ansible used, and only then touch Ansible settings. The kit at the end, a baseline ansible.cfg and a checklist, exists so the next timeout takes 10 minutes instead of an afternoon.
What UNREACHABLE means to Ansible
Ansible separates two kinds of failure, and the difference decides what happens to the rest of the run. UNREACHABLE means Ansible could not establish or keep a working connection through its connection plugin, usually SSH, so the task never ran. Ansible removes the host from the remaining tasks of the play and counts it under unreachable in the recap. FAILED means the connection worked and the module ran but returned an error. That host also drops out of further tasks by default, but the cause lives on the host, not on the path to it.
The SSH part of the message is just as precise. "Connection timed out" says the client sent TCP SYN packets to the host and port and got no answer before its ConnectTimeout expired. Ansible passes its own timeout setting, 10 seconds by default, into that OpenSSH option. Nothing replied, neither a server nor a rejection. "Connection refused" would be a different story: a TCP reset arrived, so the host is reachable and nothing listens on that port.
Read this way, the first block of the error message stops being noise. Ansible says it could not connect, the SSH client says the TCP handshake never completed, and the address in the message, 10.20.4.17 port 22, is the exact target. That address is not always what you think it is. It comes from ansible_host if set, otherwise from the inventory name resolved through DNS, and it can differ from the address in your head or in the cloud console.
There is one more practical consequence. Because unreachable hosts drop out of the play, a run against 43 hosts can report success while 3 machines received none of the changes. In the recap, look at the unreachable= column, not just failed=. Teams that gate deployments on the playbook exit code are protected, since unreachable hosts make the run exit non-zero. Teams that set ignore_unreachable: true to keep long runs going should know they are trading visibility for completion.
Timed out, refused, denied: three different failures
The SSH layer produces several messages that look alike in red text and point to completely different fixes.
| Message from ssh | What it proves | Usual cause |
|---|---|---|
| connect to host ... port 22: Connection timed out | No reply to SYN within ConnectTimeout | Firewall dropping packets, wrong IP, host down, routing |
| connect to host ... port 22: Connection refused | Host reachable, no listener | sshd stopped, sshd on another port |
| Could not resolve hostname | DNS lookup failed | Inventory name not in DNS, wrong resolver on control node |
| Permission denied (publickey) | TCP and SSH worked, auth failed | Wrong user, wrong key, key not authorized |
| Host key verification failed | Server key does not match known_hosts | Rebuilt host with reused IP |
| Connection timed out during banner exchange | TCP connected, SSH handshake stalled | Overloaded sshd, MTU problems, slow DNS lookups on the server |
Only the first row is the subject here in the strict sense, but the last row is worth separating from it. A timeout during the banner exchange means TCP worked. The fix lives on the server or in the middle of the path, not in a firewall rule for port 22.
Timeouts specifically have a short list of causes. A security group, network ACL or host firewall silently drops the SYN instead of rejecting it, which is the default behaviour of most cloud firewalls.
The IP is wrong: a private address used from a control node outside the network, a stale address of a terminated instance, or an IPv6 address on a path that only routes IPv4. The host is down or still booting. Or a route between the control node and the subnet is missing, which happens after VPN or peering changes.
The three hosts in the opening scene sit in the same subnet as forty healthy ones. That narrows it. Subnet-level rules and routing are probably fine, so the difference is per host: an instance-level security group, a host firewall, a different IP than expected, or machines that were simply not running.
Reproduce the exact SSH command Ansible runs
Ansible does not have a special network stack. It runs the OpenSSH client with a set of options. When you can run the same command by hand, you can test fixes in seconds instead of rerunning a play.
Start by asking Ansible which address and user it will use:
ansible-inventory -i inventories/prod --host web07
ansible -i inventories/prod web07 -m ansible.builtin.ping -vvvv
The first command prints the merged host variables, including ansible_host, ansible_user, ansible_port and any ansible_ssh_common_args. The second prints, at verbosity 4, a line starting with SSH: EXEC ssh that contains the full command line: control path, ConnectTimeout, user, port, proxy settings and the target address. Copy that line, remove the trailing remote command, and run it yourself with -vvv.
ssh -vvv -o ConnectTimeout=10 -o ControlMaster=no \
-o User=deploy -p 22 10.20.4.17
Watch where the debug output stops. If it ends at Connecting to 10.20.4.17 port 22 and then times out, the TCP handshake failed and nothing about keys or users matters yet. If it gets to Connection established and stalls later, you are in the banner or key exchange territory from the table above.
Then test the network path without SSH at all, which removes the client configuration from the picture:
nc -vz -w 5 10.20.4.17 22
traceroute -T -p 22 10.20.4.17
nc gives a clean yes or no within 5 seconds. traceroute -T sends TCP SYN packets to port 22 and shows the last hop that responds, which often points straight at the firewall or gateway dropping traffic. Run the same two commands against one of the forty healthy hosts as a control. If the healthy host answers and the broken one does not, from the same machine, in the same minute, the problem is the broken host or its rules.
Keep the timing of these tests in mind. A firewall that drops packets makes nc wait the full 5 seconds and print a timeout, while a host whose sshd is stopped answers with refused in a few milliseconds. That difference alone, a long wait against an instant answer, sorts most cases into the right half of the table before you open any console.
One detail about multiplexing: Ansible uses ControlMaster=auto and ControlPersist=60s by default, so an existing master connection can hide or delay a fresh connect attempt. Adding -o ControlMaster=no to manual tests, as above, makes every test a real new connection.
The network path: security groups, bastions and private IPs
Most timeouts in cloud environments come from the space between the control node and the host, and that space has changed since the playbook was written.
The control node moved. A playbook that ran from an engineer's laptop over VPN now runs from a CI runner in another VPC or region. The runner's address is not in the security group that allows port 22, so every SYN is dropped. The fix is a rule for the runner's subnet, or better, a bastion that the runner reaches and that reaches the hosts.
The inventory returns the wrong address. Dynamic inventory plugins choose which attribute becomes ansible_host. With the amazon.aws.aws_ec2 plugin, for example, the hostnames and compose options decide whether you get public IPs, private IPs or DNS names. A control node outside the VPC cannot reach private addresses without a bastion or a VPN, and a recent change to the plugin configuration can flip the address type for every host at once.
A bastion is configured but bypassed. For hosts behind a jump host, set the proxy in inventory or group variables, so it applies only to hosts that need it. In a file such as group_vars/private_web.yml:
ansible_ssh_common_args: "-o ProxyJump=deploy@bastion.example.net:22"
ProxyJump requires OpenSSH 7.3 or later on the control node. On older clients, the equivalent is a ProxyCommand with ssh -W %h:%p. When only some hosts time out, check whether they are the ones in a group that does not get this variable.
Hosts that are still booting look identical to hosts behind a broken firewall. Playbooks that create instances and configure them in the same run should wait explicitly instead of hoping the first task lands after sshd starts:
- name: Wait until new hosts accept SSH
ansible.builtin.wait_for_connection:
delay: 10
timeout: 300
That task retries for up to 300 seconds, after an initial 10-second delay, and fails clearly if the host never becomes reachable. A blanket increase of the global timeout would slow down every unreachable host instead.
In the opening scene, the three hosts turned out, in this illustrative telling, to be instances launched from an older template with a different security group that allowed SSH only from the previous VPN range. Same subnet, different rule, timeout on every connect.
Mistakes that turn one slow host into a failed run
Timeouts are often made worse by settings chosen to make them go away. The common ones:
- Raising
timeoutto 60 or 120 seconds globally. Every truly unreachable host now holds a fork for 2 minutes per attempt, and withretries = 2that is about 6 minutes before Ansible gives up on it, while healthy hosts queue behind the occupied forks. - Setting
forksto 50 or 100 behind a single bastion. OpenSSH's defaultMaxStartups 10:30:100on the bastion starts randomly dropping unauthenticated connections after 10 concurrent ones, which shows up as resets and intermittent timeouts on random hosts. - Adding
retriesunder[ssh_connection]to mask a firewall problem. Retries help with flaky links, not with packets that are always dropped. - Using
ignore_unreachable: trueon whole plays, so hosts silently miss changes and drift from the rest of the fleet. - Relying on DNS names that resolve differently on the control node and in the cloud console, for example a split-horizon zone returning public addresses to CI and private ones to laptops.
- Testing with a manual
ssh web07that uses~/.ssh/configentries Ansible does not see when it runs as a different user in CI. - Reusing IP addresses for rebuilt hosts and then disabling host key checking globally to silence the resulting errors, which removes protection against a real interception on the same path.
- Leaving retry logic to rerunning the whole playbook by hand, instead of limiting the rerun to the failed hosts.
The last item has a cheap fix. Retry files are disabled by default in modern Ansible, but the recap lists the unreachable hosts, and a rerun with --limit web07,web11,web23 after fixing the cause touches only those 3 machines.
Starter kit: a baseline config and a checklist for the repo
Keep connection settings in the repository's ansible.cfg, so CI and laptops behave the same way.
[defaults]
inventory = inventories/prod
forks = 20
timeout = 15
host_key_checking = True
interpreter_python = auto_silent
[ssh_connection]
ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s -o ServerAliveInterval=15 -o ServerAliveCountMax=4
pipelining = True
retries = 2
A timeout of 15 seconds gives slower links some room without making dead hosts expensive. forks = 20 stays well under typical bastion limits. ServerAliveInterval=15 with ServerAliveCountMax=4 drops a dead session after about 60 seconds instead of hanging. pipelining reduces the number of SSH operations per task, though it requires that requiretty is not enforced in sudoers on the targets. retries = 2 covers transient drops, not broken rules.
The checklist to run when a host is unreachable with a timeout:
- Read the address and port in the error message, then confirm them with
ansible-inventory --host. - Run
nc -vz -w 5to that address and port from the control node, and the same against a healthy host. - Replay the
SSH: EXECline from-vvvvwith-o ControlMaster=noand see where it stops. - Check that the host is running and finished booting in the cloud console.
- Compare the security groups or firewall rules of the failing host with a healthy one in the same subnet.
- Confirm the control node's current source IP or subnet is allowed, especially after moving runs to CI.
- Check whether the host should go through a bastion and whether its group gets
ansible_ssh_common_args. - If TCP connects but the session stalls, look at sshd load,
MaxStartupsand MTU on VPN paths. - Rerun only the failed hosts with
--limitonce the cause is fixed.
Run that checklist against the three hosts from the opening and it stops at the fifth line: their security group, inherited from an older launch template, still allowed port 22 only from the previous VPN range. Allowing the current control node's range in that group fixes the cause, and a rerun with --limit web07,web11,web23 brings the three machines level with the rest. If the fleet later moves to session managers, such as the community.aws.aws_ssm connection plugin or gcloud compute ssh --tunnel-through-iap, the checklist still applies, with agent health and IAM policies in place of security group rules. The recap after the rerun is the test: 43 hosts ok, none unreachable.