首页 文章

Ansible忽略任务中的错误,如果任何任务有错误,则在剧本结束时失败

提问于
浏览
29

我正在学习Ansible . 我有一个清理资源的剧本,我希望剧本忽略每一个错误并一直持续到最后,如果有错误则最后失败 .

我可以忽略错误

ignore_errors: yes

如果这是一项任务,我可以做一些事情(来自ansible错误捕获)

- name: this command prints FAILED when it fails
  command: /usr/bin/example-command -x -y -z
  register: command_result
  ignore_errors: True

- name: fail the play if the previous command did not succeed
  fail: msg="the command failed"
  when: "'FAILED' in command_result.stderr"

我怎么会在最后失败?我有几个任务,我的“何时”条件是什么?

3 回答

  • 10

    使用Fail模块 .

    • 对于发生错误时需要忽略的每个任务,使用ignore_errors .

    • 在任何任务执行失败时设置一个标志(例如,result = false)

    • 在剧本的最后,检查是否设置了标志,并且根据该标志,执行失败

    • fail:msg =“执行因错误而失败 . ”
      when:flag ==“失败”

    更新:

    使用register存储您在示例中显示的任务结果 . 然后,使用这样的任务:

    - name: Set flag
      set_fact: flag = failed
      when: "'FAILED' in command_result.stderr"
    
  • 21

    您可以将所有可能在块中失败的任务包装起来,并对该块使用 ignore_errors: yes .

    tasks:
      - name: ls
        command: ls -la
      - name: pwd
        command: pwd
    
      - block:
        - name: ls non-existing txt file
          command: ls -la no_file.txt
        - name: ls non-existing pic
          command: ls -la no_pic.jpg
        ignore_errors: yes
    

    阅读块here中有关错误处理的更多信息 .

  • 1

    失败模块效果很好!谢谢 .

    我必须在检查之前定义我的事实,否则我会得到一个未定义的变量错误 .

    当我用引号设置事实并且没有空格时,我遇到了问题 .

    这有效:

    set_fact: flag="failed"
    

    这引发了错误:

    set_fact: flag = failed
    

相关问题