首页 > 解决方案 > 通过运行shell脚本设置环境后如何执行命令?

问题描述

我正在使用 ansible 连接到远程 Linux 机器。我想执行一个应用程序特定的命令,它会给我应用程序版本。但在此之前,必须执行一个 shell 脚本,它将为上述命令执行设置环境。

目前,每个任务似乎都在单独的外壳中执行

我想执行psadmin -v,执行后/ds1/home/has9e/CS9/psconfig.sh

- command: "{{ item }}"
  args:
    chdir: "/ds1/home/has9e/CS9/"
  with_items:
   - "./psconfig.sh"
   - "psadmin -v"
  register:  ptversion
  ignore_errors: true

错误是:

failed: [slc13rog] (item=./psconfig.sh) => {
    "changed": false,
    "cmd": "./psconfig.sh",
    "invocation": {
        "module_args": {
            "_raw_params": "./psconfig.sh",
            "_uses_shell": false,
            "argv": null,
            "chdir": "/ds1/home/has9e/CS9/",
            "creates": null,
            "executable": null,
            "removes": null,
            "stdin": null,
            "warn": true
        }
    },
    "item": "./psconfig.sh",
    "msg": "[Errno 8] Exec format error",
    "rc": 8
}

标签: shellansible

解决方案


command模块(和模块)在shell子进程中执行您的命令。这意味着如果您运行一个设置环境变量的 shell 脚本,这对任何后续命令都没有影响:变量在子进程中设置,然后退出。

如果您希望在 shell 脚本中设置的环境变量影响后续命令,则需要使它们都成为同一个 shell 脚本的一部分。例如:

- shell: |
    ./psconfig.sh
    psadmin -v
  args:
    chdir: "/ds1/home/has9e/CS9/"
  register:  ptversion
  ignore_errors: true       

在这里,我们使用 YAML|运算符将文字块传递给shell模块,但我们可以改为:

- shell: "./psconfig.sh;psadmin -v"
  args:
    chdir: "/ds1/home/has9e/CS9/"
  register:  ptversion
  ignore_errors: true       

这两种选择在功能上是相同的。在这两种情况下,我们都将psconfig.sh脚本引入 shell 环境,然后在同一个 shell 中psadmin运行任务。


推荐阅读