如何在一行中通过SSH执行命令替换

时间:2019-02-07 19:24:26

标签: bash ansible

我需要检查remote_server的正常运行时间,如果它小于600秒,如果大于它,则打印通过,否则打印失败。我知道可以在这里使用docs,但我需要一行完成。以下是两次使用壳一衬板和HERE doc的尝试失败

使用一行的原因:我将把该行提供给ansible的shell模块。我尝试遵循以下命令,并使用单引号防止扩展,但它不起作用。

ssh remote_server "if [ '$(grep -oP \"^[0-9]+\" /proc/uptime)' -le 600 ];then echo  remote_server Failed ;exit 1;else echo remote_server passed ;fi"

我还尝试了以下方法将条件转换为多行。但它也不起作用。

  - name: get the uptime of all nodes
    shell:  |
    ssh {{ item }} " bash <<'EOF'
    if [ '$(grep -oP \"^[0-9]+\" /proc/uptime)' -le 600 ];then
        echo  {{ item }} Failed ;
        exit 1;
     else
        echo {{item }} passed ;
     fi
     "
     EOF
    with_items:
      - "{{ node_list.stdout_lines }}"
    become: true

违规行似乎是:

       ssh {{ item }} " bash <<'EOF'
        if [ '$(grep -oP \"^[0-9]+\" /proc/uptime)' -le 600 ];then
        ^ here

exception type: <class 'yaml.scanner.ScannerError'>
exception: while scanning a simple key
  in "<unicode string>", line 51, column 9
could not find expected ':'
  in "<unicode string>", line 52, column 9

更新:

 shell:  ssh {{ item }} 'if [ "$(grep -oP '^[0-9]+' /proc/uptime) -le 600 ]; then echo failed; exit 1; else echo passed; fi'

错误:

"start": "2019-02-07 15:05:36.740756",
"stderr": "bash: -c: line 0: unexpected EOF while looking for matching `\"'\nbash: -c: line 1: syntax error: unexpected end of file",
"stderr_lines": [
    "bash: -c: line 0: unexpected EOF while looking for matching `\"'",
    "bash: -c: line 1: syntax error: unexpected end of file"
],
"stdout": "",
"stdout_lines": []

0 个答案:

没有答案