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:
- name: Install de-servers configurations
hosts: de-servers
roles:
- de-server-setup
- name: Install uk-servers configurations
hosts: uk-servers
roles:
- uk-server-setup
- name: Do some other job on de-servers (cannot be done until uk-servers is installed)
hosts: de-servers
roles:
- de-servers-rest-of-jobs
In role de-servers-setup role the ssh port is changed from 22 to 8888, so when the last task is called it fails because it cannot connect to host through 22 port. How to overcome this ssh port change?
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 theansible_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:
My playbook looks like this:
Finally, right after the SSH server is configured and the port has been changed I have this:
Easy way, edit /etc/ansible/hosts:
and you can test it by issuing a ping:
and the response would be:
In the role
de-server-setup
add a task to change theansible_port
host variable.I need to change the ssh ports on the hosts I manage and I want to use Ansible to do it. Essentially, Ansible uses the following logic to manage it's SSH connections:
where "self.port" is the port specification from the host inventory, or an override via the "-e" parameter, or an explicit declaration of the variables "ansible_port" and/or "ansible_ssh_port". The recommended solution to changing ports is to employ the "wait_for" and "when" modules in "pre_tasks", but there are many inadequacies to this approach, particularly when many hosts are involved and especially when you want to use different ports on different hosts.
I cloned and patched the ssh plugin (versions 1 and 2) to change the logic as follows:
The patch, by itself, makes no changes on the target nodes but allows connections to succeed even if the ports on the nodes haven't changed yet. With the patch, it is now very easy to write roles/tasks to change ssh ports to whatever is in the host inventory.
If you're interested, you can find the patch and samples of how use it at https://github.com/crlb/ansible; the README.md contains additional information.
The only thing I can think of that might work would be to create ssh aliases for your hosts. In your
.ssh/config
:Then use these aliases in your Ansible inventory:
And the defined groups then respectively in your plays: