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:

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


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

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

You can just use the force param of the template module:

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

Or naming the task ;-)

    - name: Create file from template if it doesn't exist already.
        src: somefile.j2
        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.

  • 2
    my answer uses stat, because at the time of the question/answer there was no force argument avaialable for template – Teftin Jul 9 '16 at 13:13

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

  - name: Check that the somefile.conf exists
      path: /etc/somefile.conf
    register: stat_result

  - name: Copy the template, if it doesnt exist already
      src: somefile.j2
      dest: /etc/somefile.conf
    when: stat_result.stat.exists == False   
  • 1
    I prefer this answer because it names it's tasks :) – Asfand Qazi Jun 23 '15 at 13:36

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

  • Back when this question was asked, the force parameter was not implemented. Today, this answer describes best practice! – dirdi Aug 5 '20 at 13:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.