2014-09-22 31 views
10

我試圖編寫一個任務,它運行ldapmodify語句的列表,並且只在任何返回代碼不是0或68(對象媒體鏈接存在):根據返回代碼在`with_items`任務上使用`failed_when`

- 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 

不工作時,產生的錯誤:

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

但是,如果我評論的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" 

旁註sameas可能是Jinja2的其他版本equalto,如果你想知道。

回答

17

那麼,事實證明我是這麼做太複雜了。問題是: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 

產生想要的結果。

循環變量result後填充有具有各results鍵的詳細信息的摘要字典。

但是,由於我無法找到任何使用result.results與過濾器鏈的例子,我只會留下這個問題,希望其他人可能會覺得它有用。 (我確定最終我會終日想再看一遍;))

感謝sivel上#ansible指出了這一點。