使用Ansible shell模块调用时,shell脚本给出的输出不正确

时间:2019-09-04 07:06:12

标签: shell ansible format

我有希望在目标节点上运行的check.sh脚本:

cat check.sh

str=`echo $1 | sed -e 's#[\][\]n# #g'`
echo $str>check.row

假设用自变量中的单个空格替换\ n并将其保存在check.row文件中。

当我在目标服务器上手动运行它时,我得到了很好的输出结果,如下所示:

bash -x ./check.sh '/fin/app/01/scripts\\n/fin/app/01/sql'
++ echo '/fin/app/01/scripts\\n/fin/app/01/sql'
++ sed -e 's#[\][\]n# #g'
+ str='/fin/app/01/scripts /fin/app/01/sql'
+ echo /fin/app/01/scripts /fin/app/01/sql

生成的check.row看起来不错,如下所示:

[user1@remotehost1 ~]$ cat check.row 
/fin/app/01/scripts /fin/app/01/sql

但是,当我使用ansible shell或命令模块运行相同命令时,却没有得到预期的结果。

下面是我的剧本:

  tasks:
   - copy:
       src: "{{ playbook_dir }}/files/check.sh"
       dest: "~/"
       mode: 0754

   - set_fact:
       install_dir: "{{ hostvars[\'localhost\'][\'command_result\'].stdout.split('\t')[2] }}"

   - shell: "bash -x  ~/check.sh '{{ install_dir }}' > ~/check_rollback.log"

请参阅下面的ansible调试输出:

changed: [10.8.44.55] => {
    "changed": true, 
    "cmd": "bash -x  ~/check.sh '/fin/app/01/scripts\\n/fin/app/01/sql' > ~/check_rollback.log", 
    "delta": "0:00:00.118943", 
    "end": "2019-09-04 10:50:16.503745", 
    "invocation": {
        "module_args": {
            "_raw_params": "bash -x  ~/check.sh '/fin/app/01/scripts\\n/fin/app/01/sql' > ~/check_rollback.log", 
            "_uses_shell": true, 
            "argv": null, 
            "chdir": null, 
            "creates": null, 
            "executable": null, 
            "removes": null, 
            "stdin": null, 
            "stdin_add_newline": true, 
            "strip_empty_ends": true, 
            "warn": true
        }
    }, 
    "rc": 0, 
    "start": "2019-09-04 10:50:16.384802", 
    "stderr": "++ echo '/fin/app/01/scripts\\n/fin/app/01/sql'\n++ sed -e 's#[\\][\\]n# #g'\n+ str='/fin/app/01/scripts\\n/fin/app/01/sql'\n+ echo '/fin/app/01/scripts\\n/fin/app/01/sql'", 
    "stderr_lines": [
        "++ echo '/fin/app/01/scripts\\n/fin/app/01/sql'", 
        "++ sed -e 's#[\\][\\]n# #g'", 
        "+ str='/fin/app/01/scripts\\n/fin/app/01/sql'", 
        "+ echo '/fin/app/01/scripts\\n/fin/app/01/sql'"
    ], 
    "stdout": "", 
    "stdout_lines": [] }

这是ansible运行的check.row文件输出:

[user1@remotehost1 ~]$ cat check.row 
/fin/app/01/scripts\\n/fin/app/01/sql

现在可以打印\ n来代替单个空格。

我正在使用最新版本的ansible。

一个人可以轻松地复制此问题。您能否建议我为什么收到此问题以及如何解决此问题?

1 个答案:

答案 0 :(得分:1)

首先,您正在使用仅指定shell命令的shell模块,而您在其中错误地使用了bash。

shell: "bash -x  ~/check.sh '{{ install_dir }}' > ~/check_rollback.log"

第二,您可以看到您的任务导致了错误,如附件输出中所示。

Stdout为空,我们可以在stderr中看到错误。

第三,如果要使用bash,可以使用命令模块,如下所示,

- command: "bash -x  ~/check.sh '{{ install_dir }}' > ~/check_rollback.log"

我还建议您在 check.sh 脚本中进行以下更改,

#!/bin/bash
echo $1 # You can check the value that is passed to the script
str=$(echo "$1" | sed -e 's/\\n/ /g') # Use quotes around your variable
echo "$str" > check.row

它工作正常。