Using Ansible with bastion or jump host with variables

Sometimes due to network configuration or security reasons you can’t access a host directly, but should use intermediate host, so-called bastion or jump host.

My presious article on this topic, using ssh config file: Using Ansible with bastion host.

Another option is using variables. This approach is more flexible: it is easier to define different bastion hosts for different hosts and groups with variables.

Simplest option is to directly mention bastion host address and user:

group_vars/all/ansible_ssh.yml:

ansible_ssh_common_args: "-o ProxyCommand=\"ssh <bastion user>@<bastion address> -o Port=<bastion ssh port> -W %h:%p\""

And of course don’t forget to reset that variable for the bastion host itself:

host_vars/bastion_host/ansible_ssh.yml:

ansible_ssh_common_args: ""

Downside of simple option is duplicating bastion host coordinates in variables and in inventory. More complex setup to avoid the duplication:

group_vars/all/ansible_ssh.yml:

ansible_ssh_proxy_command: >-
  {% if bastion_host is defined and bastion_host != '' %}
  ssh {{ hostvars[bastion_host]['ansible_ssh_user'] }}@{{ hostvars[bastion_host]['ansible_ssh_host'] }}
  -o Port={{ hostvars[bastion_host]['ansible_ssh_port'] | default(22) }}
  -W %h:%p
  {% endif %}

ansible_ssh_common_args: >-
  {% if bastion_host is defined and bastion_host != '' %}
  -o ProxyCommand="{{ ansible_ssh_proxy_command }}"
  {% endif %}

# Default bastion host for all hosts
bastion_host=bastion1

And you still have to mention that bastion host itself doesn’t need this:

host_vars/bastion_host/ansible_ssh.yml:

bastion_host: ""


License: This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License Share: share on reddit share on hacker news share on facebook share on twitter share on linkedin share on slashdot

No comments

You today

Comments are closed