I'm trying to use Ansible for automating the setup process of new server instances. One of the setup tasks changes the default SSH port, therefore requiring me to update the hosts list.
Is it possible to automate this by having Ansible fallback to a specified port if the connection could not be established to the default SSH port?
You could try a local_action on the hosts to see if you can connect to the respective ports and register the one that succeeds and set that as a fact. You want to turn off gather facts because otherwise the setup module will fail when it tries to connect with the hosts which have already been reconfigured. Once you've done this play just add others below with gather_facts and all the rest.
It was pointed out to me that this will blow out the time for playbooks where you use this. You could also set ansible_ssh_port in the vars section of plays that should only be run on hosts with reconfigured ssh port. e.g.
@RichardSalts thanks for getting me started with this. I used nc to check ports which should be a lot faster. This is my bootstrap.xml:
Tested using ansible 1.5 (devel 3b8fd62ff9) last updated 2014/01/28 20:26:03
Since you probably deploy your ssh config early, you really should keep this simple. Just configure your inventory with the target
ansible_ssh_port
and use-e
when deploying your ssh configuration for the first time:Note that
ansible_ssh_port
is deprecated in 2.0 (superseded byansible_port
)I also needed similar functionality, so I forked and patched the Ansible ssh plugin hoping that Ansible Inc. would adopt it; they didn't. It tests non-std ssh port specifications to see if they are open and reverts to the default ssh port if not. It's a very small patch, available at https://github.com/crlb/ansible.
If you have list of ports and you want to check them all and use one that working, you can use this in your playbook:
I came up with a robust idempotent task list to put in a role to change the SSH port and handle connecting to the right port without having to change your inventory file. I've posted the details on my blog: https://dmsimard.com/2016/03/15/changing-the-ssh-port-with-ansible/
If you changed ssh port (default=22) of your remote server, you can use this param when running
ansible-playbook
command:1954 is your custom ssh port
Ref: https://docs.ansible.com/ansible/latest/cli/ansible-playbook.html
---- UDPATE ----
You can edit file:
inventory/hosts
add this:
ansible_port=<port>