ansible - delete unmanaged files from directory?

前端 未结 7 2090
情深已故
情深已故 2021-01-30 06:38

I want to recursively copy over a directory and render all .j2 files in there as templates. For this I am currently using the following lines:

7条回答
  •  不知归路
    2021-01-30 07:14

    Here's something I came up with:

    - template: src=/source/directory{{ item }}.j2 dest=/target/directory/{{ item }}
      register: template_results
      with_items:
        - a_list.txt
        - of_all.txt
        - templates.txt
    - set_fact:
        managed_files: "{{ template_results.results|selectattr('invocation', 'defined')|map(attribute='invocation.module_args.dest')|list }}"
    
    - debug:
        var: managed_files
        verbosity: 0
    
    - find:
        paths: "/target/directory/"
        patterns: "*.txt"
      register: all_files
    - set_fact:
        files_to_delete: "{{ all_files.files|map(attribute='path')|difference(managed_files) }}"
    
    - debug:
        var: all_files
        verbosity: 0
    - debug:
        var: files_to_delete
        verbosity: 0
    
    - file: path={{ item }} state=absent
      with_items: "{{ files_to_delete }}"
    
    • This generates the templates (however which way you want), and records the results in 'template_results'
    • The the results are mangled to get a simple list of the "dest" of each template. Skipped templates (due to a when condition, not shown) have no "invocation" attribute, so they're filtered out.
    • "find" is then used to get a list of all files that should be absent unless specifically written.
    • this is then mangled to get a raw list of files present, and then the "supposed to be there" files are removed.
    • The remaining "files_to_delete" are then removed.

    Pros: You avoid multiple 'skipped' entries showing up during deletes.

    Cons: You'll need to concatenate each template_results.results if you want to do multiple template tasks before doing the find/delete.

提交回复
热议问题