Ansible:仅在目标文件不存在时复制模板

我正在使用Ansible 1.6.6来configuration我的机器。

我的手册中有一个模板任务 ,用于从Jinja2模板创build目标文件:

 tasks: - template: src=somefile.j2 dest=/etc/somefile.conf 

如果它已经存在,我不想取代somefile.conf 。 Ansible有可能吗? 如果是这样,怎么样?

    您可以使用stat检查文件是否存在,然后仅在文件不存在时才使用模板。

     tasks: - stat: path=/etc/somefile.conf register: st - template: src=somefile.j2 dest=/etc/somefile.conf when: not st.stat.exists 

    你可以使用模板模块的强制参数:

     tasks: - template: src=somefile.j2 dest=/etc/somefile.conf force=no 

    或者命名任务;-)

     tasks: - name: Create file from template if it doesn't exist already. template: src: somefile.j2 dest:/etc/somefile.conf force: no 

    从Ansible模板模块文档:

    强制:默认是yes,当内容不同于源时,将replace远程文件。 如果不是,则只有在目的地不存在的情况下才会传输文件。

    其他答案使用stat因为force参数是在写入之后添加的。

    您可以先检查目标文件是否存在,然后根据结果的输出做出决定。

     tasks: - name: Check that the somefile.conf exists stat: path: /etc/somefile.conf register: stat_result - name: Copy the template, if it doesnt exist already template: src: somefile.j2 dest: /etc/somefile.conf when: stat_result.stat.exists == False 

    据我所知,最简单的解决scheme是使用模板模块中的“force = no”属性