2017-04-18 56 views
1

我想在一个合理的剧本中运行一个命令任务,如果失败,我想运行救援部分。我想故障状态是如果命令失败(退出状态!= 0)和标准错误输出不包含某些字符串,这样区分Ansible中的Ansible错误和任务错误?

- block: 
    - name: some command 
     command: "command {{ my_var }}" 
     register: command_status 
     failed_when: command_status.rc != 0 and "Some text" not in command_status.stderr 
     changed_when: false 
    rescue: 
    - name: error occurred. Rolling back 
     command: rescue-command 

东西上面的问题是,如果变量my_var是不是以上定义,该命令将失败(与像the field 'args' has an invalid value, which appears to include a variable that is undefined消息和救援部分将运行,这是不希望的。有什么办法避免Ansible考虑到Ansible特定错误VS在剧中从实际的命令来错误?

我有种预期rc返回值只能是特定的命令,但这似乎并不如此。

我正在Ansible 2.3

回答

1

错误的源极之间不能直接区分,但更多的是黑客对你的使用情况:

您可以command_status.cmd添加一个检查救援款。如果模块失败,变量command_status.cmd不会被定义,因此救援任务将不会运行:

- block: 
    - name: some command 
     command: "command {{ my_var }}" 
     register: command_status 
     failed_when: command_status.rc != 0 and "Some text" not in command_status.stderr 
     changed_when: false 
    rescue: 
    - name: error occurred. Rolling back 
     command: rescue-command 
     when: command_status.cmd is not defined 
+0

谢谢你。我给这是一个尝试,但我环顾四周,找不到关于此的任何文件。你可以进入?。在这个返回值被究竟是如何设置的详细信息是什么 – ByteFlinger

+0

文档找不到任何地方 – techraf

+0

对不起,按下注释按钮太快文档上。加利福尼亚返回值 – ByteFlinger

0

我将扩大@ techraf与明确fail答案意外错误的情况下,否则Ansible将继续执行任务好像没有什么不幸发生。

- block: 
    - name: some command 
     command: "command {{ my_var }}" 
     register: command_status 
     failed_when: command_status.rc != 0 and "Some text" not in command_status.stderr 
     changed_when: false 
    rescue: 
    - fail: 
     msg: Unexpected error occurred "{{ command_status.msg }}" 
     when: command_status.failed_when_result is undefined 

    - name: Expected error occurred. Rolling back 
     command: rescue-command 

如果错误是意外这将失败主机(因为failed_when_result定义,如果与failed_when任务完成);如果预期错误(命令失败,因为failed_when声明,救援命令将被应用。

+0

从我的经验,如果发生错误,救援节将只允许你运行一个命令时,它完全失败,所以我不确定你的意思之前 – ByteFlinger

+0

我经验是完全不同的。如果一个块的救援部分中的最后一个任务是'ok',则将执行该块之后的任务。 –