我正在通过 Ansible 执行 shell 命令。
有时我没有完整的文件夹名称。假设我有 dirname solr4.7.0
。
在 shell 中,我可以输入cd solr*
.
但在ansible我不能这样做:
chdir=/var/solr*
有什么解决方法吗?
我正在通过 Ansible 执行 shell 命令。
有时我没有完整的文件夹名称。假设我有 dirname solr4.7.0
。
在 shell 中,我可以输入cd solr*
.
但在ansible我不能这样做:
chdir=/var/solr*
有什么解决方法吗?
chdir=
不。例如,模块的参数command
不支持通配符。
您可以使用寄存器变量来存储命令的输出来完成您想要的操作ls
:
- shell: ls -d solr*
register: dir_name
- command: some_command
args:
chdir: "{{ dir_name.stdout }}"
但坦率地说,这是一个丑陋的解决方案。最好只使用实际的目录名称。如果它在不同的主机上有所不同,您可以使用主机变量来适当地设置它。
正如 Larsks 所写,关键是使用register
,但该代码不适用于我当前的 ansible 版本。所以这里更正一个:
- shell: ls -d solr*
register: dir_name
- command: chdir={{ item }} some_command
with_items: dir_name.stdout_lines
在命令行上使用 ansible 来执行 ad hoc 命令,通配符非常有用,例如查看文件是否存在于所有系统上。
我也很难做到:
$ ansible production -a "ls /mypath/*xxx*"
但是将其包装在 bash -c '...' 中有效:
$ ansible production -a "bash -c 'ls /mypath/*xxx*'"
像这样定义的任务可以解决问题:
- name: Move internal directories and files
command: bash -c 'mv /tmp/parent-dir/* /opt/destination/'
这有点骇人听闻,但我发现如果您将使用通配符的命令放入脚本中,然后使用 ansible 'script' 命令运行该脚本,通配符就可以了。
- name: "some command that needs to use a wildcard"
script: /script_containing_wildcard_commands.sh