Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 23 down vote accepted

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

  - 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 at 13:36

Your Answer


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.