Ansible 仅当文件不';不存在

Ansible 仅当文件不';不存在,ansible,Ansible,我尝试只设置模板,如果相应的文件不存在。我目前有以下内容,它总是创建文件 - name: Setup templates template: src={{ item }} dest={{ item | basename | regex_replace('\.j2','') }} with_fileglob: ../templates/*.j2 如果有三个模板 t1.j2 t2.j2 t3.j3 目标中存在两个文件 t1 t3 我只希望运行并复制t2.j2模板 我见过用state

我尝试只设置模板,如果相应的文件不存在。我目前有以下内容,它总是创建文件

- name: Setup templates
  template: src={{ item }} dest={{ item | basename | regex_replace('\.j2','') }}
  with_fileglob: ../templates/*.j2
如果有三个模板

  • t1.j2
  • t2.j2
  • t3.j3
目标中存在两个文件

  • t1
  • t3
我只希望运行并复制t2.j2模板


我见过用state命令注册变量的方法,但还没有弄清楚如何用with_fileglob注册变量。

您可以使用
stat
模块来确定有关文件的信息:

---

- name: File exist?
  stat: path=/tmp/not-exist
  ignore_errors: true
  register: myfile

- debug: var=myfile

- name: Setup templates
  template: src={{ item }} dest={{ item | basename | regex_replace('\.j2','') }}
  with_fileglob: ../templates/*.j2
  when: myfile.stat.exists == false

- debug: msg="Print if file exist"
  when: myfile.stat.exists == true

此设置将跳过上一个任务,但将执行模板。

结果表明,您可以传递一个force参数。这将仅在文件不存在时复制模板

- name: Setup templates
  template: src={{ item }} dest={{ item | basename | regex_replace('\.j2','') }} force=no
  with_fileglob: ../templates/*.j2

这适用于一个文件,但我想让“设置模板”检查文件glob中的每个项目是否存在,如果不存在,则有条件地为该特定模板运行。您可以轻松编写自己的lookup\u插件,以实现您所描述的功能。在我看来,这将是最干净、最易读的选择。旧答案,我可能找错了方向,但这不应该说force=no来实现你想要的吗?@tink是的,应该是force=no。谢谢。