My complete solution to this problem was to create a generic piece, imported at the top of all other pieces, that checks the status of the non-standard ansible_port defined in the inventory. If the port is open, continue as usual. If it is not open, check port 22 and set it to ansible_port , if so.
Later, when the SSH server is configured for the first time, and the default port is replaced with my non-standard port, I then manually ansible_port fact ansible_port in my ansible_port so that any further Ansible connections in the current start work as expected.
My inventory looks like this:
[webservers] web01.somedomain.com ansible_port=1234
My play 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"
source share