在Ansible中使用通配符查找远程文件

时间:2019-07-24 05:25:46

标签: ansible

我使用shell模块运行一个Java命令,该命令会创建一个带有后缀为随机字符串的文件。

我需要随后使用uri模块将此文件发布。

我正在尝试使用stat module和通配符来查找文件,但是找不到它。

- stat:
    path: "{{ my_dir }}/info-*"
  register: info

- debug:
    msg: "info isn't defined (path doesn't exist)"
  when: info.stat.exists == False

我还能如何找到文件名?

1 个答案:

答案 0 :(得分:1)

状态模块需要完整路径。

但是,可以通过使用 find模块,因为它允许使用通配符。

  

路径要搜索的目录的路径列表。

     

模式一种或多种(shell或正则表达式)模式,其类型由use_regex选项控制。   这些模式将要返回的文件列表限制为其基名至少与指定的一种模式匹配的文件。可以使用列表指定多个模式。此参数需要一个列表,...

- find:
    paths:
      - "{{ my_dir }}"
    patterns:
      - "info-*"
  register: info

- debug:
    msg: "{{ info.files }}"

问题。 “ I run a java command using the shell module which creates a file with a random string suffixed to this. I need to subsequently POST this file using the uri module.

答案。可以使用找到的第一个文件

- debug:
    var: info.files.0.path

,但可能有更多文件与模式info-*相匹配。一个可靠的解决方案是使java command ... which creates a file with a random string suffixed返回文件名。或者,也可以改用tempfile模块。