shell 让ansible运行一个脚本,而不使用退出代码停止ssh连接

kdfy810k  于 2023-08-07  发布在  Shell
关注(0)|答案(3)|浏览(122)

我们有一个看起来像下面这样的任务

- name: Check if that created
  script: verification.sh
  register: verification
  changed_when: verification.rc == 1

字符串
上面的任务运行一个脚本,它在失败或成功时返回一个退出信号。示例部分为

if [[ "$item" == "$name" ]]; then
        printf "TEST"
        exit 1
    fi


这里的问题是,当返回一个非0值的退出信号时,ansible中的ssh似乎会终止,并给出如下错误

TASK [Test Task] ******************
fatal: [default]: FAILED! => {"changed": true, "failed": true, "rc": 1, "stderr": "Shared connection to 127.0.0.1 closed.\r\n", "stdout": "TEST", "stdout_lines": ["TEST"]}


然而,当我们在脚本中返回一个退出信号时,这就可以工作了
我猜这是因为在远程主机上运行了“exit”,然后它终止了ssh连接。
我们如何绕过这一点,并在没有错误的情况下返回退出信号。

tez616oj

tez616oj1#

您可以使用failed_when来控制定义失败的内容:

- name: Check if that created
  script: verification.sh
  register: verification
  changed_when: verification.rc == 1
  failed_when: verification.rc not in [0,1]

字符串
当退出代码既不是0也不是1时,这将给予失败。

r55awzrz

r55awzrz2#

通常,playbook将停止在任务失败的主机上执行更多步骤。有时候,你想继续。为此,编写一个类似于以下内容的任务:
http://docs.ansible.com/ansible/playbooks_error_handling.html#ignoring-failed-commandsIgnoring失败的命令

- name: Check if that created
  script: verification.sh
  register: verification
  changed_when: verification.rc == 1
  ignore_errors: yes

字符串

cwdobuhd

cwdobuhd3#

我想这个答案是这样的:https://stackoverflow.com/a/44538536/2909072
但在我的例子中,我做了一些类似的事情(在我的script.sh中):

# error handle inside a class (function)
if [ "${script_mail_status}" = "Error" ]; then
    echo "Error, check email/log for details. Bye!"
    # Fail the script and playbook
    exit 2
fi

# end of script (EOF), bye!
exit 0

字符串

**注意:**在我的公司,脚本退出0表示“成功”,1表示“成功但有错误”,2表示“错误/严重”。

在我的情况下,我将尝试的剧本可以是这样的:

- name: Check if that created
  script: script.sh
  register: result
  changed_when: result.rc in [0,1]
  failed_when: result.rc not in [0,1]


检查这个是否有效……

相关问题