Skip to content
Latchkey

Molecule "Failed to connect to the host via ssh" in CI

Some Molecule setups drive instances over SSH (delegated, vagrant, or cloud drivers) rather than the container connection. If the instance has no sshd running, the key is wrong, or the host is unreachable, converge fails at the connection step.

What this error means

Ansible marks the instance UNREACHABLE with "Failed to connect to the host via ssh: Connection refused" or "Permission denied (publickey)" during converge.

Molecule
fatal: [instance]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect
to the host via ssh: ssh: connect to host 10.0.0.5 port 22: Connection refused",
"unreachable": true}

Common causes

No sshd running in the instance

A container image without an SSH server cannot accept the ssh connection Molecule attempts. Container scenarios usually use the local/container connection instead.

Wrong key, user, or the instance is still booting

A missing or wrong private key, a user mismatch, or connecting before the instance finishes booting all produce ssh failures.

How to fix it

Use the container connection for container drivers

For docker/podman instances, let the driver use its native connection rather than ssh.

molecule/default/molecule.yml
provisioner:
  name: ansible
  connection_options:
    ansible_connection: community.docker.docker

Wait for ssh and pin the key for ssh-based drivers

  1. Ensure the instance runs sshd and finished booting before converge.
  2. Point ansible_ssh_private_key_file at the correct key.
  3. Set the right ansible_user for the image.
molecule/default/molecule.yml
provisioner:
  name: ansible
  inventory:
    host_vars:
      instance:
        ansible_user: ci
        ansible_ssh_private_key_file: ./id_ci

How to prevent it

  • Use the container-native connection for container drivers.
  • For ssh drivers, wait for the port and provision the key first.
  • Match ansible_user to the image default.

Frequently asked questions

What causes ""Failed to connect to the host via ssh""?
A container image without an SSH server cannot accept the ssh connection Molecule attempts. Container scenarios usually use the local/container connection instead.
How do I fix "Failed to connect to the host via ssh"?
For docker/podman instances, let the driver use its native connection rather than ssh.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card