Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using `failed_when` on a `with_items` task depending on return codes

I am trying to write a task which runs a list of ldapmodify statements and only want it to fail if any of the return codes are not 0 or 68 (object allready existed):

- name: add needed LDAP infrastructure
  action: command ldapmodify -x -D '{{ ADMINDN }}' -w '{{ LDAPPW }}' -H {{ LDAPURI }} -c -f {{ item }}
  register: result
  failed_when: "result.results | rejectattr('rc', 'sameas', 0) | rejectattr('rc', 'sameas', 68) | list | length > 0"
  # ignore_errors: true
  with_items:
    - a.ldif
    - b.ldif

Does not work, producing the error:

error while evaluating conditional: result.results | rejectattr('rc', 'sameas', 0) | rejectattr('rc', 'sameas', 68) | list | length > 0

However if I comment the failed_when and use ignore_errors, the following tasks produce the correct results. While I can use this workaround to solve my problem, I would like to understand why the failed_when version is not working, as I would find that more elegant.

- debug: var="result.results | rejectattr('rc', 'sameas', 0) | rejectattr('rc', 'sameas', 68) | list | length > 0"
- fail: msg="failure during ldapmodify"
  when: "result.results | rejectattr('rc', 'sameas', 0) | rejectattr('rc', 'sameas', 68) | list | length > 0"

Sidenote sameas might be equalto in other versions of jinja2, in case you are wondering.

like image 956
IsoLinearCHiP Avatar asked Sep 22 '14 19:09

IsoLinearCHiP


1 Answers

Well, it turns out I was going about it much too complicated. The problem was: Ansible runs failed_when after every iteration of the loop. As such I simply need to access result.rc:

- name: add needed LDAP infrastructure
  action: command ldapmodify -x -D '{{ ADMINDN }}' -w '{{ LDAPPW }}' -H {{ LDAPURI }} -c -f {{ item }}
  register: result
  # As per comment from user "ypid"
  failed_when: ( result.rc not in [ 0, 68 ] )
  # failed_when: ( result.rc != 0 ) and ( result.rc != 68 )
  with_items:
    - a.ldif
    - b.ldif

produces the wanted result.

After the loop the variable result is filled with a summary dictionary which has the details of each item in the results key.

But since I was not able to find any examples of using result.results with filter chains I will just leave this question up, hoping someone else might find it useful. ( I'm sure I will eventually want to look it up again some day ;) )

Thanks to sivel on #ansible for pointing this out.

like image 182
IsoLinearCHiP Avatar answered Nov 13 '22 04:11

IsoLinearCHiP