0

I have disable_root role, which creates admin user and disables root user from connecting to server via ssh. When I rerun playbook with this role for second time I get unreachable error (which is ok, as I just disabled it).

I'd like to skip this role in such case and continue with other roles (which would run as a admin user). How can I do this?

This is my playbook (disbale_root uses ansible_user: root var)

- hosts: webservers
  roles:
    - disable_root
    - common
    - nginx
Marcin Doliwa
  • 3,639
  • 3
  • 37
  • 62
  • I guess it is hard to guess in prior if the "user exists" without having a valid ansible_user. Ansible cannot do much if the ssh login itself fails. So, I guess you are trying to switch to "admin" user in case disable_root fails, then you can just add another user variable and update ansible_user globally in case of failure. – Krishnom May 07 '19 at 02:01
  • 1
    In case you just want to catch that failure, and do some stuffs, please check https://stackoverflow.com/questions/54540617/try-catch-in-ansible-with-timeout-on-task – Krishnom May 07 '19 at 02:02

1 Answers1

1

One playbook shall connect to the remote host as root, if necessary, or as admin if this user has already been created. This can be done with remote_user (see Ansible remote_user vs ansible_user ).

Let's create the playbook to disable root and enable admin

> cat play-disable-root.yml
- hosts: webservers
  remote_user: 'root'
  tasks:
    - include_role:
        name: disable_root
      when: play_disable_root|default(false)

In the first play import this playbook if admin can't connect to the remote host

- hosts: webservers
  remote_user: 'admin'
  tasks:
    - delegate_to: localhost
      command: ping -c1 "{{ inventory_hostname }}"
      register: result
      ignore_errors: true
    - set_fact:
        play_disable_root: true
      when: result.rc != 0

- import_playbook: play-disable-root.yml

in the second play proceed with remaining roles

- hosts: webservers
  remote_user: 'admin'
  roles:
    - common
    - nginx

Both first and second play may be put into one playbook.

(code not tested)

Updates:

  • it's not possible to conditionally import playbooks
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63