Search code examples
dockersshansiblewindows-10

Ansible in Docker conatiner failed to connect to Hetzner host via ssh


I'm pretty new to Ansible and I'm trying to run a playbook with Docker (Windows 10) but it fails to ssh into the Hetzner cloud.

I have created a Makefile to run Ansible in Docker

# Makefile
run_playbook:
    @docker run --rm \
        -v "C:/Users/myuser/.ssh/hetzner/id_rsa:/root/.ssh/id_rsa" \
        -v "C:/Users/myuser/.ssh/hetzner/id_rsa.pub:/root/.ssh/id_rsa.pub" \
        -v $(CURDIR)/ansible.cfg:/etc/ansible/ansible.cfg \
        -v $(CURDIR):/myapp-ansible \
        -w /myapp-ansible \
        williamyeh/ansible:alpine3 \
        ansible-playbook -i staging site.yml -vvv

This is the staging inventory

[myapp]
<HETNER_SERVER_NAME> ansible_host=<HETZNER_SERVER_IP> ansible_user=root

and this is the ansible.cfg

# ansible.cfg
[defaults]
host_key_checking = false
roles_path = /myapp-ansible/roles

[privilege_escalation]
become = True
become_method = sudo
become_user = root

The problem is that when I run the make run_playbook command, I get the error Failed to connect to the host via ssh.

So I tried to manually connect from the docker container to see what happens and this is the result

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0755 for '/root/.ssh/id_rsa' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key "/root/.ssh/id_rsa": bad permissions
root@<HETZNER_SERVER_IP>'s password:

I tried to change the id_rsa permissions with sudo chmod 600 /root/.ssh/id_rsa, but it seems to have no effect

$ ls -l /root/.ssh
-rwxr-xr-x    1 root     root          2610 Aug 25 13:38 id_rsa
-rwxr-xr-x    1 root     root           577 Aug 25 13:38 id_rsa.pub
-rw-r--r--    1 root     root           176 Aug 26 08:42 known_hosts

So I tried to change the id_rsa permissions directly in Windows as suggested here, but I get the same result as before.

To be noted that in Windows I was able to ssh with Putty with the same private key without problem.

Thanks in advance


Solution

  • After googling a lot I have found this article, so I changed the run_playbook as below:

    run_playbook:
        @docker run -t --rm \
            -v "C:/Users/myuser/.ssh/hetzner/id_rsa:/tmp/.ssh/id_rsa" \
            -v "C:/Users/myuser/.ssh/hetzner/id_rsa.pub:/tmp/.ssh/id_rsa.pub" \
            -v $(CURDIR):/myapp-ansible \
            -w /myapp-ansible \
            williamyeh/ansible:alpine3 \
            /bin/sh -c "cp -R /tmp/.ssh /root/.ssh && chmod 700 /root/.ssh && chmod 644 /root/.ssh/id_rsa.pub && chmod 600 /root/.ssh/id_rsa"
            ansible-playbook -i staging site.yml