【问题标题】:Ansible: enforce pipefailAnsible:强制管道失败
【发布时间】:2016-01-23 03:20:24
【问题描述】:

今天早些时候,我们遇到了一个由以下 shell 管道引起的严重问题:

- name: get remote branches
  shell: git ls-remote -h git@bitbucket.org:orga/repo.git | sed 's_.*refs/heads/__g'
  register: branches_remote

git命令失败,但是整个管道的返回码是0。This is default bash/sh behavior

要解决此问题,您可以在 sh/bash 中使用 set -o pipefailset -e。是否可以在我的所有shell 命令中以ansible 的方式执行此操作,最好是全局执行?

【问题讨论】:

  • ansible 的git module 不适合你吗?
  • 我们需要提取一个远程分支名称,稍微操作一下,然后将它存储在一个变量中。如果没有shell 也能做到这一点,那当然很棒。
  • set -e 不能替代 set -o pipefail (与问题中的“或”所暗示的相反);如果您希望脚本通过任何失败管道组件的第一个失败退出状态而不继续执行后面的命令,则需要 both
  • ...也就是说,shell: 默认使用/bin/sh,对于set -o pipefail 根本不保证可用。
  • 可以将此作为library/commands/command 的本地补丁来实现,但是... eww。

标签: bash shell error-handling pipe ansible


【解决方案1】:

一般来说,你应该尝试使用 shell 命令作为最后的手段,因为它们往往有点脆弱。如果您需要将 shell 模块与任何 shell 选项一起使用,只需将其作为命令管道的一部分提交,如下所示。可执行参数强制使用 bash shell。

[user@ansible ~]$ ansible myhost -m shell -a "executable=/bin/bash set -o pipefail && false | echo hello there"
myhost | FAILED | rc=1 >>
hello there

[user@ansible ~]$ ansible myhost -m shell -a "executable=/bin/bash set -o pipefail && true | echo hello there"
myhost | success | rc=0 >>
hello there

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    相关资源
    最近更新 更多