Ansible: copy template only when destination file does not exist

Solution 1:

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

Solution 2:

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.