Ansible: Check if my user exists on remote host, else use root user to connect with ssh
You can test the connection with local_action
first.
Ansible need to know how to connect to the host for sure, otherwise it will trigger host unreachable
error and skip remaining tasks for that host.
Something like this:
- hosts: myservers
gather_facts: no # or it will fail on the setup step
tasks:
- name: Test user
local_action: "command ssh -q -o BatchMode=yes -o ConnectTimeout=3 {{ inventory_hostname }} 'echo ok'"
register: test_user
ignore_errors: true
changed_when: false
- name: Do useful stuff
remote_user: "{{ test_user | success | ternary(omit, 'root') }}"
command: echo ok
A more native and elegant way to test your SSH connection is with the Ansible ping module (which verifies the end-to-end SSH connection, not ICMP), and to use the playbook keyword ignore_unreachable
, which was added in Ansible 2.7.
The technique below puts SSH testing into its own play where facts are not gathered; subsequent plays will gather facts as normal:
---
###
## First play: Dynamically configure SSH user
##
- hosts: "{{ host_group }}"
gather_facts: false # don't try to ssh yet!!
vars:
ansible_ssh_user: "{{ username }}"
tasks:
- name: "Test SSH connection"
ping: # <-- no args needed
ignore_unreachable: true
ignore_errors: true
changed_when: false
register: ssh_test
- name: "Fall back to root user?"
when: ssh_test.unreachable is defined
connection: local
set_fact:
ansible_ssh_user: root
###
## Next play: Install Stuff
###
- hosts: "{{ host_group }}"
tasks:
- name: Install openssl on Ubuntu or Debian
# ...