Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with errors coming from ansible roles

Tags:

ansible

I have been calling a playbook having multiple roles, each roles signifies a TESTCASE. I need to run the playbook without failing it if one of the role fails during execution. For which I am using ignore_errors: yes. However, this truly ignores error, I need to print at the end the name of the ROLES which are failed ? is it possible ?

- hosts: WEB
  gather_facts: no
  vars:
  roles:
    - { role: CHECK_CONNECTION, ignore_errors: yes, tags: always }
    - { role: CHECK_CPU, ignore_errors: yes, tags: always }
    - { role: CHECK_MEM, ignore_errors: yes, tags: always }

Question: How to execute whole playbook and at the end print the failed roles ?

like image 374
monk Avatar asked Apr 04 '19 16:04

monk


People also ask

How do you handle failure in Ansible?

By default Ansible stops executing tasks on a host when a task fails on that host. You can use ignore_errors to continue on in spite of the failure. The ignore_errors directive only works when the task is able to run and returns a value of 'failed'.

What happens when one playbook fails a task?

If you use ignore_errors, ansible will continue attempting to run tasks against that host. The default workflow is to fail, then ignore that host for the rest of the playbook. Then at the end, admin researches why the hosts failed, fixes them, then reruns the playbook against the ones that failed.

How do you update Ansible roles?

To update a locally installed role to a new or different version, use the ansible-galaxy install command with the version and --force option. You may also need to manually update any dependent roles to support this version.

What is one option that Ansible gives you to check your playbook for syntax errors?

You may want to verify your playbooks to catch syntax errors and other problems before you run them. The ansible-playbook command offers several options for verification, including --check , --diff , --list-hosts , --list-tasks , and --syntax-check .


1 Answers

An option would be to use the rescue section of Blocks

Create include_role.yml

- name: include role
  block:
    - include_role:
        name: "{{ item_my_role }}"
  rescue:
    - set_fact:
        failed_roles: "{{ failed_roles|default([]) + [ item_my_role ] }}"

and loop include_tasks. It is not possible to loop blocks.

vars:
  my_roles:
    - CHECK_CONNECTION
    - CHECK_CPU
    - CHECK_MEM
tasks:
- include_tasks: include_role.yml
  loop: "{{ my_roles }}"
  loop_control:
    loop_var: item_my_role
- debug:
    var: failed_roles|default([])

Use loop_control loop_var and create unique variable, e.g. item_my_role, avoiding potential conflict inside the included role. If the variable is used inside the included role the following rescue section will add the wrong item to the list.

like image 164
Vladimir Botka Avatar answered Nov 15 '22 11:11

Vladimir Botka