SSH to remote server using ansible

Solution 1:

Given that you do not use Paramiko for ssh (transport = ssh), Ansible will fully use your ~/.ssh/config. Therefore you can globally define all connection rules in your ssh configuration.

If for some reason you want Ansible to not use your default ssh config but provide an separate configuration, you can define this in your ansible.cfg:

[ssh_connection]
ssh_args= -F "/path/to/ssh/config/specifically/for/ansible"

In your ssh config then set up the connection rules. To stick with your example:

Host HostA
  HostName real-host-name-A.com

Host HostB
  HostName real-host-name-B.com
  ProxyCommand ssh -q HostA nc %h %p

Host HostC
  HostName real-host-name-C.com
  ProxyCommand ssh -q HostB nc %h %p
  • Connections to A are direct
  • Connections to B go through A
  • Connections to C go through B, which goes through A

Solution 2:

For Ansible 2.0 and above you can do the following:

Step #1: Edit the hosts file and add a line for your target host:

my-target-host ansible_host=10.10.105.23 ansible_ssh_private_key_file=~/.ssh/private_key  ansible_ssh_common_args='-o ProxyCommand="ssh -W %h:%p -q my-jump-node"'

Notice the use of the ansible_ssh_common_args='-o ProxyCommand="ssh -W %h:%p -q my-jump-node"' which handles the proxying through the jump node.

Step #2: In the ~/.ssh/config file define your my-jump-node:

Host my-jump-node
  Hostname <IP_ADDRESS>
  User ubuntu
  Port 22
  IdentityFile /root/.ssh/nhc-moho/id_rsa # <<< Local path of private key
  ControlMaster auto
  ControlPath /tmp/ansible-%r@%h:%p
  ControlPersist 5m

Step #3: Notice in step #1 above we have ansible_ssh_private_key_file=~/.ssh/private_key. This is the private_key stored at the my-jump-node and it's corresponding public key is stored at my-target-host.

The important thing to remember here is:

YOU HAVE TO COPY THIS PRIVATE KEY FROM THE my-jump-node MACHINE TO YOUR LOCAL MACHINE WHERE YOU RUN ANSIBLE, OR ELSE IT WILL FAIL TO CONNECT TO my-target-host

Step #4: Test it.

ansible my-target-host -m shell -a "echo 'TESTING'"