Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 31 down vote accepted

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
share|improve this answer
    
Oh, great. Many thanks! ) – Slava Fomin II Jul 5 '14 at 12:32

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

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.

Not sure why the others answer use stat...

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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