通过ansible使用模式时sed找不到文件
sed not finding file when using a pattern through ansible
我有以下角色:
---
- name: Replaces a string in a file
command: sed 's/'"{{ target_string }}"'/'"{{ new_string }}"'/g' -i {{ target_file_name }}
chdir="{{ target_file_location }}"
调用如下:
- { role: string_replace_in_file, target_string: "localhost", new_string: "{{ myValue }}", target_file_name: "*.scripts.js", target_file_location: "/path/to/folder" }
我要修改的文件是aea342.scripts.js
我得到以下输出:
failed: [myMachine] => {"changed": true, "cmd": ["sed", "s/localhost/myValue/g", "-i", ".*.scripts.js"], "delta": "0:00:00.031107", "end": "2016-02-02 14:26:21.715652", "rc": 2, "start": "2016-02-02 14:26:21.684545", "warnings": ["Consider using template or lineinfile module rather than running sed"]}
stderr: sed: can't read .*.scripts.js: No such file or directory
当我在我的机器上手动 运行 sed 's/localhost/myValue/g' -i *.scripts.js
但是它工作。
来自 command module 上的 Ansible 文档:
It will not be processed through the shell, so variables like $HOME and operations like "<", ">", "|", and "&" will not work
这也意味着globs like "*.scripts.js" won't be expanded when you use the command module. If you need to use "*" then you should switch to using the shell module。顾名思义,它通过命令 shell 运行 执行操作,因此“*”之类的内容将被正确扩展。
布鲁斯是正确的。使用 shell
扩展 glob。我没有测试这个。你能试试吗:
- name: Replaces a string in a file
shell: sed -i "s/<search>/<replace>/g" target_file_location/target_file_name(s)
我有以下角色:
---
- name: Replaces a string in a file
command: sed 's/'"{{ target_string }}"'/'"{{ new_string }}"'/g' -i {{ target_file_name }}
chdir="{{ target_file_location }}"
调用如下:
- { role: string_replace_in_file, target_string: "localhost", new_string: "{{ myValue }}", target_file_name: "*.scripts.js", target_file_location: "/path/to/folder" }
我要修改的文件是aea342.scripts.js
我得到以下输出:
failed: [myMachine] => {"changed": true, "cmd": ["sed", "s/localhost/myValue/g", "-i", ".*.scripts.js"], "delta": "0:00:00.031107", "end": "2016-02-02 14:26:21.715652", "rc": 2, "start": "2016-02-02 14:26:21.684545", "warnings": ["Consider using template or lineinfile module rather than running sed"]}
stderr: sed: can't read .*.scripts.js: No such file or directory
当我在我的机器上手动 运行 sed 's/localhost/myValue/g' -i *.scripts.js
但是它工作。
来自 command module 上的 Ansible 文档:
It will not be processed through the shell, so variables like $HOME and operations like "<", ">", "|", and "&" will not work
这也意味着globs like "*.scripts.js" won't be expanded when you use the command module. If you need to use "*" then you should switch to using the shell module。顾名思义,它通过命令 shell 运行 执行操作,因此“*”之类的内容将被正确扩展。
布鲁斯是正确的。使用 shell
扩展 glob。我没有测试这个。你能试试吗:
- name: Replaces a string in a file
shell: sed -i "s/<search>/<replace>/g" target_file_location/target_file_name(s)