Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: Test if SSH login possible without FATAL error?

Tags:

ansible

I have a setup playbook that takes a freshly installed linux instance, logs in as the default user (we'll call user1), creates another user (we'll call user2), then disables user1. Because user1 can only access the instance before this set of tasks is executed, the tasks are in a special playbook we have to remember to run on new instances. After that, all the common tasks are run by user2 because user1 no longer exists.

I want to combine the setup and common playbooks so we don't have to run the setup playbook manually anymore. I tried to create a task to see which user exists on the instance to make the original setup tasks conditional by attempting to login via SSH as user1. The problem is that if I try the SSH login for either user, ansible exits with a FATAL error because it can't login: user2 doesn't exist yet on new instances or user1 has been disabled after the setup playbook executes.

I believe testing the login via SSH is the only way to determine externally what condition the instance is in. Is there a way to test SSH logins without getting a FATAL error to then execute tasks conditionally based on the results?

like image 578
Dave Stern Avatar asked Oct 28 '13 18:10

Dave Stern


2 Answers

One approach would be to use shell via a local_action to invoke a simple ssh command to user1 and see if it succeeds or not. Something along these lines:

- name: Test for user1
  local_action: shell ssh user1@{{ inventory_hostname }} "echo success"
  register: user1_enabled

Then you could use something like this in another task to see if it worked:

  when: user1_enabled.stdout.find("success") != -1
like image 174
Bruce P Avatar answered Oct 30 '22 14:10

Bruce P


With Ansible >= 2.5 it is possible to use the wait_for_connection_module (https://docs.ansible.com/ansible/2.5/modules/wait_for_connection_module.html).

- name: Wait 600 seconds for target connection to become reachable/usable
  wait_for_connection:
like image 23
Christian Berendt Avatar answered Oct 30 '22 14:10

Christian Berendt