Ansible:强制执行管道故障

Nic*_*mer 5 error-handling bash shell pipe ansible

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

- name: get remote branches
  shell: git ls-remote -h git@bitbucket.org:orga/repo.git | sed 's_.*refs/heads/__g'
  register: branches_remote
Run Code Online (Sandbox Code Playgroud)

git命令失败,而是整个管道的返回码为0。这是默认的bash / sh的行为

要解决此问题,在 sh/bash 中,您可以set -o pipefailset -e. 是否有可能在 ansible 中做到这一点,最好是对我的所有shell命令全局进行?

Dav*_*ier 4

一般来说,您应该尝试使用 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
Run Code Online (Sandbox Code Playgroud)