48

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?

62

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
43

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

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

Or naming the task ;-)

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.

  • 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
10

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
    I prefer this answer because it names it's tasks :) – Asfand Qazi Jun 23 '15 at 13:36
-3

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

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.