2015-07-02 31 views
2

如果相应文件不存在,我尝试只设置模板。我目前有以下总是创建文件。仅在文件不存在的情况下才有可用模板

- 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模板来运行和复制..

我见过的方法与状态的命令,但天堂”注册一个变量t想出了如何用with_fileglob来做到这一点。

回答

1

原来你可以传递一个参数。如果文件不存在,那只会复制模板。

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

您可以使用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 

此安装程序将跳过最后的任务,但将执行模板。

+0

这适用于一个文件,但我希望'安装程序模板'检查文件glob中的每个项目是否存在,并有条件地针对该特定模板运行(如果没有)。 – Joshua

+0

您可以轻松地编写自己的lookup_plugin,以执行您所描述的操作。在我看来,它将是最干净和最可读的选项。 – Vor

相关问题