Ansible, Bastion Host, ProxyCommand

Ansible Playbook

The Ansible playbook we’ll use in this example only contains the bare necessities and has the following structure:

bastion_playbook/
ansible.cfg
inventory
ssh.cfg

Hosts

Let’s define our servers in the inventory file:

[bastion]
54.171.0.0
[app_servers]
172.16.1.1
172.16.2.1

SSH

Ansible uses SSH for virtually all its operations and since it allows us to specify a custom configuration file we can utilize SSH’s tried and proven ProxyCommand which was created for exactly what we want to achieve.

Host 172.16.*
ProxyCommand ssh -W %h:%p ubuntu@54.171.0.0
Host *
ControlMaster auto
ControlPath ~/.ssh/mux-%r@%h:%p
ControlPersist 15m

Ansible Config

Now we want to tell Ansible to use our custom ssh.cfg file, thankfully the Ansible guys have made this pretty easy through ansible.cfg:

[ssh_connection]
ssh_args = -F ssh.cfg
control_path = ~/.ssh/mux-%r@%h:%p
$ ansible app_servers -i inventory -u ubuntu -m ping

Gist

Here’s a gist with all the code used in this example.

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store