我有 bash 命令:
cat <<< $(jq --indent 4 '.autoload."psr-4" += { "Modules\\": "Modules/" }' me/composer.json) > me/composer.json
但是在 ansible 中我得到了更多的错误。
---
- name: modules autoload
shell: |
cat <<< $(jq --indent 4 '.autoload."psr-4" += { "Modules\\": "Modules/" }' me/composer.json) > me/composer.json
fatal: [127.0.0.1]: FAILED! => {"changed": true, "cmd": "cat <<< $(jq --indent 4 '.autoload.\"psr-4\" += { \"Modules\\\\\": \"Modules/\" }' me/composer.json) > me/composer.json", "delta": "0:00:00.001537", "end": "2023-03-13 01:06:28.268890", "msg": "non-zero return code", "rc": 2, "start": "2023-03-13 01:06:28.267353", "stderr": "/bin/sh: 1: Syntax error: redirection unexpected", "stderr_lines": ["/bin/sh: 1: Syntax error: redirection unexpected"], "stdout": "", "stdout_lines": []}
或
---
- name: modules autoload
command: |
cat <<< $(jq --indent 4 '.autoload."psr-4" += { "Modules\\": "Modules/" }' me/composer.json) > me/composer.json
fatal: [127.0.0.1]: FAILED! => {"changed": true, "cmd": ["cat", "<<<", "$(jq", "--indent", "4", ".autoload.\"psr-4\" += { \"Modules\\\\\": \"Modules/\" }", "me/composer.json)", ">", "me/composer.json"], "delta": "0:00:00.001982", "end": "2023-03-13 01:08:33.239162", "msg": "non-zero return code", "rc": 1, "start": "2023-03-13 01:08:33.237180", "stderr": "cat: unrecognized option '--indent'\nTry 'cat --help' for more information.", "stderr_lines": ["cat: unrecognized option '--indent'", "Try 'cat --help' for more information."], "stdout": "", "stdout_lines": []}
给定文件进行测试
shell> cat me/composer.json
{"autoload": {"psr-4": {"X": "Y"}}}
命令
shell> cat <<< $(jq --indent 4 '.autoload."psr-4" += {"Modules": "Modules"}' me/composer.json) > me/composer.json.new
按预期工作
shell> cat me/composer.json.new
{
"autoload": {
"psr-4": {
"X": "Y",
"Modules": "Modules"
}
}
}
在 Ansible 模块中运行此命令shell:
将运行字符串放入变量中的block。这样你就摆脱了两层转义。
默认情况下,模块 shell 通过 /bin/sh 运行命令。将可执行文件更改为 bash,或您测试过命令的另一个 shell
默认情况下,该命令在有效用户的主目录中执行。将其更改为存储文件的绝对路径。在下面的示例中,在本地主机上运行,目录 me 位于 playbook 目录中。查看特殊变量playbook_dir
- shell:
cmd: '{{ cmd }}'
chdir: "{{ playbook_dir }}"
executable: /usr/bin/bash
vars:
cmd: >-
cat <<< $(jq --indent 4 '.autoload."psr-4" += {"Modules": "Modules"}' me/composer.json) > me/composer.json.new
register: out
- debug:
var: out
给予
TASK [debug] **********************************************************************************************************************************************************************************
ok: [localhost] =>
out:
changed: true
cmd: 'cat <<< $(jq --indent 4 ''.autoload."psr-4" += {"Modules": "Modules"}'' me/composer.json) > me/composer.json.new'
delta: '0:00:00.051676'
end: '2023-03-13 01:44:07.508255'
failed: false
msg: ''
rc: 0
start: '2023-03-13 01:44:07.456579'
stderr: ''
stderr_lines: []
stdout: ''
stdout_lines: []
新文件已创建
shell> cat me/composer.json.new
{
"autoload": {
"psr-4": {
"X": "Y",
"Modules": "Modules"
}
}
}