58

I'm using Ansible 1.6.6 to provision my machine.

There is a template task in my playbook that creates destination file from Jinja2 template:

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

I do not want to replace somefile.conf if it already exists. Is it possible with Ansible? If so, how?

4 Answers4

71

You can just use the force param of the template module with force=no

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

From the Ansible template module docs:

force: the default is yes, which will replace the remote file when contents are different than the source. If no, the file will only be transferred if the destination does not exist.

Other answers use stat because the force parameter was added after they were written.

4wk_
  • 376
sanzante
  • 729
69

You can check for file existence using stat, and then use template only if file does not exist.

tasks:
  - stat: path=/etc/somefile.conf
    register: st
  - template: src=somefile.j2 dest=/etc/somefile.conf
    when: not st.stat.exists
Teftin
  • 1,947
11

You can first check that the destination file exists or not and then make a decision based on the output of it's result.

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   
-1

According to me, the easiest solution is to use the attribute "force=no" from the template module