With ansible, how do I check if a file is managed by ansible?

While writing an Ansible playbook for a new server environment, I'm wanting to check to see if a configuration file is already managed by Ansible or not. If it is not, I want to add an extra step to back up the current config file, but I don't want to make a back up every time the playbook runs.

Here's the role I have currently, which takes in file and fact variables:

---
- name: Check if file exists
  stat:
    path: "{{file}}"
  register: filestat

- block:
    - command: "head -n1 {{file}}"
      check_mode: no
      changed_when: no
      when: file is defined
      register: ismanaged

    - set_fact: '{{fact}}={{"ansible" in ismanaged|lower}}'
  when: filestat.stat.exists


- set_fact: '{{fact}}=no'
  when: not filestat.stat.exists

- name: Clean up
  set_fact:
    filestat:
    ismanaged:

Essentially you pass the filename you want to check, and the fact variable name to set. It checks if the first line of the file contains "ansible", then sets the fact to either "yes" or "no". This works for Ansible-managed files that contain the {{ ansible_managed }} tag in the first line, but I'm sure this will miss some.

Any suggestions?


You shouldn't think that way when working with Ansible. If you want to manage a file with Ansible, just do it. Don't mix manual and automatic work, because this makes your playbook more complex and unreadable and is unnecessary.

If you want to care about changes, use backup: true as argument for lineinfile, template, etc... In that case, Ansible will make a backup only, when the file changes (it calls diff to verify that). So - not any run of your playbook would generate a new backup file. Only the first time.

After that - Ansible would not generate a backup, except you change the file manually (then Ansible would override it and copy the old file as backup) or your template (as an example is changed). In both cases the backup file is something, you may want.