Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: ignoring errors in a loop

Tags:

linux

ansible

yum

I need to install a number of packages on linux boxes. Some (few) of the packages may be missing for various reasons (OS version, essentially)

 - vars:
      pkgs:
         - there_1
         - not_there_1
         - there_2
           ...

but I would like too manage them from a single playbook. So I cannot stick them all in a single

yum: state=latest name="{{pkgs}}"

Because missing packages would mess the transaction so that nothing gets installed.

However, the obvious (and slow) one by one install also fails, because the first missing package blows the entire loop out of the water, thusly:

  - name Packages after not_there_1 are not installed
    yum: state=latest name="{{item}}" 
    ignore_errors: yes
    with_items: "{{ pkgs  }}"

Is there a way to ignore errors within a loop in such a way that all items be given a chance? (i.e. install errors behave as a continue in the loop)

like image 583
Alien Life Form Avatar asked Apr 10 '18 14:04

Alien Life Form


1 Answers

If you need to loop a set of tasks a a unit it would be -so- nice if we could use with_items on an error handling block right?

Until that feature comes around you can accomplish the same thing with include_tasks and with_items. Doing this should allow a block to handle failed packages, or you could even include some checks and package installs in the sub-tasks if you wanted.

First setup a sub-tasks.yml to contain your install tasks:

Sub-Tasks.yml

  - name: Install package and handle errors
    block:
      - name Install package
        yum: state=latest name="{{ package_name }}"
    rescue:
      - debug:
          msg: "I caught an error with {{ package_name }}" 

Then your playbook will setup a loop of these tasks:

  - name: Install all packages ignoring errors
    include_tasks: Sub-Tasks.yml 
    vars:
      package_name: "{{ item }}"
    with_items:
      - "{{ pkgs }}"
like image 144
Tj Kellie Avatar answered Sep 21 '22 17:09

Tj Kellie