Here is the inventory file
---
[de-servers]
192.26.32.32
[uk-servers]
172.21.1.23
172.32.2.11
and my playbook is look like this:
My full solution to this was to create a common playbook imported at the top of all other playbooks that checks the status of the non-standard ansible_port
defined in the inventory. If the port is open then continue as normal. If it's not open check port 22 and set the ansible_port
fact to that if so.
Later, when the SSH server is configured for the first time and the default port is changed to my non-standard port, I then update the ansible_port
fact manually in my playbook so that any further Ansible connections in the current run will work as expected.
My inventory looks like this:
[webservers]
web01.somedomain.com ansible_port=1234
My playbook looks like this:
- name: Determine SSH port
hosts: all
gather_facts: no
remote_user: root
tasks:
- name: "Check port {{ ansible_port }}"
wait_for:
port: "{{ ansible_port }}"
state: "started"
host: "{{ inventory_hostname }}"
connect_timeout: "5"
timeout: "5"
delegate_to: "localhost"
ignore_errors: "yes"
register: ssh_port
- name: "Check port 22"
wait_for:
port: "22"
state: "started"
host: "{{ inventory_hostname }}"
connect_timeout: "5"
timeout: "5"
delegate_to: "localhost"
ignore_errors: "yes"
register: ssh_port_default
when:
- ssh_port is defined
- ssh_port.state is undefined
- name: Set SSH port to 22
set_fact:
ansible_port: "22"
when: ssh_port_default.state is defined
Finally, right after the SSH server is configured and the port has been changed I have this:
- name: Set SSH port to 1234
set_fact:
ansible_port: "1234"
In the role de-server-setup
add a task to change the ansible_port
host variable.
- name: Change ssh port to 8888
set_fact:
ansible_port: 8888