The "Permission denied" SSH error is one of the most common Ansible issues. Here are the 5 most effective solutions.

The Error

fatal: [webserver]: UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: Permission denied (publickey,password).",
    "unreachable": true
}

Solution 1: Check SSH Key Configuration

The most common cause is a missing or incorrect SSH key.

# ansible.cfg
[defaults]
private_key_file = ~/.ssh/id_ed25519
remote_user = deploy

Test SSH connectivity first:

ssh -i ~/.ssh/id_ed25519 deploy@webserver -v

Solution 2: Fix SSH Key Permissions

SSH refuses keys with incorrect permissions.

chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub
chmod 644 ~/.ssh/authorized_keys

Solution 3: Use ansible_ssh_private_key_file

Set the key per host in your inventory:

[webservers]
webserver ansible_host=192.168.1.10 ansible_user=deploy ansible_ssh_private_key_file=~/.ssh/deploy_key

Solution 4: Fix become (sudo) Permission Denied

If SSH works but tasks fail with permission denied, it's a become issue:

- name: Install package (requires sudo)
  ansible.builtin.apt:
    name: nginx
    state: present
  become: true
  become_method: sudo
  become_user: root

Run with --ask-become-pass if sudo requires a password:

ansible-playbook playbook.yml --ask-become-pass

Solution 5: Add Host to known_hosts

First connection to a new host may fail if host key checking is strict:

# ansible.cfg
[defaults]
host_key_checking = False

Or add the host key first:

ssh-keyscan webserver >> ~/.ssh/known_hosts

Quick Diagnostic Checklist

# 1. Test SSH directly
ssh -vvv user@host

# 2. Test with Ansible verbose
ansible webserver -m ping -vvvv

# 3. Check key permissions
ls -la ~/.ssh/

# 4. Check remote authorized_keys
ssh user@host "cat ~/.ssh/authorized_keys"

Conclusion

SSH Permission Denied errors in Ansible almost always come down to key configuration, file permissions, or become privileges. Start with the SSH connection test and work your way through each solution.