Introduction When Ansible cannot connect to managed hosts via SSH, the entire playbook execution fails. The "UNREACHABLE" error is one of the most common Ansible failures and can be caused by SSH misconfiguration, network issues, or authentication problems.
Symptoms - Playbook output: "UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh"}" - Error: "ssh: connect to host <ip> port 22: Connection refused" - Error: "Permission denied (publickey,password)" - Host key verification failed - SSH timeout after 10-30 seconds
Common Causes - SSH service not running on target host - SSH key not deployed to target host - Wrong SSH user specified in inventory - Firewall blocking port 22 - Host key changed (MITM warning or host rebuild)
Step-by-Step Fix 1. **Test SSH connectivity manually**: ```bash ssh -v -i ~/.ssh/ansible_key ansible@<target-ip> ```
- 1.Check Ansible inventory SSH settings:
- 2.```ini
- 3.[webservers]
- 4.web1 ansible_host=10.0.1.10 ansible_user=ansible ansible_ssh_private_key_file=~/.ssh/ansible_key ansible_port=22
- 5.
` - 6.Deploy SSH key to target host:
- 7.```bash
- 8.ssh-copy-id -i ~/.ssh/ansible_key.pub ansible@<target-ip>
- 9.# Or with Ansible:
- 10.ansible <target> -m authorized_key -a "user=ansible key='{{ lookup('file', '~/.ssh/ansible_key.pub') }}'" -k
- 11.
` - 12.Disable host key checking for dynamic environments (with caution):
- 13.```ini
- 14.[defaults]
- 15.host_key_checking = False
- 16.
` - 17.Test with Ansible ad-hoc command:
- 18.```bash
- 19.ansible <target> -m ping -vvv
- 20.
`