0

I'm trying to do an advanced version of your script where ansible running a role basing on a result of "when" condition. In my scenario ansible connects as root, creates ansible_bot user, grants him privilegies and denies access to root.

It all works on the first run, but it doesn't work on the second run, because ansible is unable to connect as a root on the first step.

I'm trying to omit that step by using the following logic, but it returns an error "error while evaluating conditional: root_connection.rc == 0".

- hosts: ansible-test
  gather_facts: false
  vars:
    - ansible_ssh_user: "{{ initial_ssh_user }}"
  tasks:
    - name: Test SSH connection for {{ initial_ssh_user }}
      local_action: shell ssh {{ initial_ssh_user }}@{{ inventory_hostname }} exit
      register: root_connection
      ignore_errors: True
  roles:
    - { role: add-ansible-bot, when: root_connection.rc == 0 }

- hosts: ansible-test
  sudo: yes
  roles:
    - common

Can you advice anything? Thanks!

user76667
  • 41
  • 5

1 Answers1

3

This is probably just an issue where your task isn't run before the role. If you really need to do what you are doing you can use pre_task::

- hosts: ansible-test
  gather_facts: false
  vars:
    - ansible_ssh_user: "{{ initial_ssh_user }}"
  pre_tasks:
    - name: Test SSH connection for {{ initial_ssh_user }}
      local_action: shell ssh {{ initial_ssh_user }}@{{ inventory_hostname }} exit
      register: root_connection
      ignore_errors: True
  roles:
    - role: add-ansible-bot
      when: root_connection.rc == 0
jarv
  • 1,303
  • 9
  • 6