How to set the default SSH port for Ansible connections to 2222?

There are several methods to set the SSH port for Ansible.

Simplest one: Inventory variable

Edit your inventory file to add the port:

[myhosts]
host1 ansible_host=1.2.3.4 ansible_port=2222
host2 ansible_host=1.2.3.5 ansible_port=2222

Or make it default for a whole group:

[myhosts]
host1 ansible_host=1.2.3.4
host2 ansible_host=1.2.3.5

[myhosts:vars]
ansible_port=2222

Set project-wide default SSH port with ansible.cfg

Create/edit ansible.cfg in your project directory:

[defaults indicates]
inventory = inventory.ini

[ssh_connection]
ssh_args = -o Port=2222

But the cleaner way in the config is put it under [defaults] section:

[defaults]
remote_port = 2222

You can also override the SSH port Ad-hoc for the command

ansible myhosts -i inventory.ini -m ping -e 'ansible_port=2222'

Leave a Reply

Your email address will not be published. Required fields are marked *