在`with_items`任务上使用`failed_when`取决于返回码

Iso*_*HiP 15 ansible ansible-playbook

我正在尝试编写一个运行ldapmodify语句列表的任务,并且如果任何返回代码不是0或68(对象已经存在),则只希望它失败:

- 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
Run Code Online (Sandbox Code Playgroud)

不起作用,产生错误:

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

但是,如果我评论failed_when并使用ignore_errors,则以下任务会产生正确的结果.虽然我可以使用此解决方法来解决我的问题,但我想了解为什么failed_when版本不能正常工作,因为我会发现它更优雅.

- 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"
Run Code Online (Sandbox Code Playgroud)

Sidenote sameas可能equalto在jinja2的其他版本中,以防你想知道.

Iso*_*HiP 30

好吧,事实证明我太复杂了.问题是:Ansible failed_when在循环的每次迭代后运行.因此我只需要访问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
Run Code Online (Sandbox Code Playgroud)

产生想要的结果.

在循环之后变量result充满了具有各自的详细信息的摘要词典项目results关键.

但由于我无法找到任何使用result.results过滤器链的例子,我只想提出这个问题,希望其他人可能会觉得它很有用.(我相信我终有一天会想再查一下;))

感谢#ansible上的sivel指出了这一点.