首页 文章

在Ansible中多次运行shell模块

提问于
浏览
2

我试图使用ansible shell模块使用不同的参数多次运行shell脚本(script1) . 但是如果任何命令失败并且返回代码不是0,则任务应该失败并退出 . 这是我到目前为止 .

- name: Run scripts
  shell: "{{ item}}"
  register: rslt
  until: rslt.rc != 0
  with_items:
    - "./script1 -f add1"
    - "./script1 -f add2"
    - "./script1 -f add3"

此任务总是运行脚本3次,即使第一个脚本失败并返回代码(rslt.rc)而不是0.我希望任务失败并退出而不运行with_items中的后续项目如果脚本的当前执行返回返回代码不是0.例如,如果第一项(“./script1 -f add1”)失败,我不希望运行第二和第三项,并且ansible任务应该失败 .

我非常感谢有关如何解决这个问题的任何建议 .

1 回答

  • 0

    不幸的是,1.9的推荐解决方案是将任务分离为单独的呼叫 .

    在Github上有一些past discussion .

    您可以使用when子句而不是until来在2.0中实现此目的 .

    在找到非零返回码后,这将跳过剩余的任务:

    - name: Run scripts
      shell: "{{ item }}"
      register: rslt
      when: rslt is undefined or rslt.rc == 0
      with_items:
         ...
    

    输出示例:

    TASK [Run scripts] *************************************************************
    changed: [localhost] => (item=exit 0)
    changed: [localhost] => (item=exit 0)
    failed: [localhost] (item=exit 1) => {"changed": true, "cmd": "exit 1",  "delta": "0:00:00.004414", "end": "2016-12-08 13:14:06.365437", "failed": true, "item": "exit 1", "rc": 1, "start": "2016-12-08 13:14:06.361023", "stderr": "", "stdout": "", "stdout_lines": [], "warnings": []}
    skipping: [localhost] => (item=exit 0)
    skipping: [localhost] => (item=exit 0)
    

相关问题