Overview

If your servers listen for SSH on a port other than 22, tell Ansible which port to use. Set it per host in the inventory when ports differ, or once for everything in ansible.cfg.

Per host
ansible_port in the inventory
For all
remote_port in ansible.cfg
One run
-e ansible_port=2222

Option 1: In the inventory (per host)

[servers]
server1 ansible_host=192.168.1.100 ansible_port=2222
server2 ansible_host=192.168.1.101 ansible_port=2200

Option 2: For a group

In group_vars/servers.yml:

ansible_port: 2222

Option 3: For every host (ansible.cfg)

[defaults]
remote_port = 2222

A host's own ansible_port still wins over this default.

Option 4: For one run

ansible-playbook -i inventory.ini check_connectivity.yml -e ansible_port=2222

Extra variables override everything else, so this applies to every host in the run.

Test it

Save this as check_connectivity.yml:

- name: Check connectivity to servers
  hosts: servers
  gather_facts: false
  tasks:
    - name: Ping the servers
      ansible.builtin.ping:

Then run:

ansible-playbook -i inventory.ini check_connectivity.yml

Each host answers pong when Ansible reaches it on the right port.