ansible - delete unmanaged files from directory?

前端 未结 7 1935
情深已故
情深已故 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:28

    I want to share my experience with this case.

    Ansible from 2.2 is had with_filetree loop provides simple way to upload dirs, links, static files and even (!) templates. It's best way to keep my config dir synchronized.

    - name: etc config - Create directories
      file:
        path: "{{ nginx_conf_dir }}/{{ item.path }}"
        state: directory
        mode: 0755
      with_filetree: etc/nginx
      when: item.state == 'directory'
    
    - name: etc config - Creating configuration files from templates
      template:
        src: "{{ item.src }}"
        dest: "{{ nginx_conf_dir }}/{{ item.path | regex_replace('\\.j2$', '') }}"
        mode: 0644
      with_filetree: etc/nginx
      when:
        - item.state == "file"
        - item.path | match('.+\.j2$') | bool
    
    - name: etc config - Creating staic configuration files
      copy:
        src: "{{ item.src }}"
        dest: "{{ nginx_conf_dir }}/{{ item.path }}"
        mode: 0644
      with_filetree: etc/nginx
      when:
        - item.state == "file"
        - not (item.path | match('.+\.j2$') | bool)
    
    - name: etc config - Recreate symlinks
      file:
        src: "{{ item.src }}"
        dest: "{{ nginx_conf_dir }}/{{ item.path }}"
        state: link
        force: yes
        mode: "{{ item.mode }}"
      with_filetree: etc/nginx
      when: item.state == "link"
    

    Next we may want delete unused files from config dir. It's simple. We gather list of uploaded files and files exist on remote server, next remove diffrence.

    But we may want to have unmanaged files in config dir. I've used -prune functionality of find to avoid clearing folders with unmanaged files.

    PS _(Y)_ sure after I have deleted some unmanaged files

    - name: etc config - Gathering managed files
      set_fact:
        __managed_file_path: "{{ nginx_conf_dir }}/{{ item.path | regex_replace('\\.j2$', '') }}"
      with_filetree: etc/nginx
      register: __managed_files
    
    - name: etc config - Convert managed files to list
      set_fact: managed_files="{{ __managed_files.results | map(attribute='ansible_facts.__managed_file_path') | list }}"
    
    - name: etc config - Gathering exist files (excluding .ansible_keep-content dirs)
      shell: find /etc/nginx -mindepth 1 -type d -exec test -e '{}/.ansible_keep-content' \; -prune -o -print
      register: exist_files
      changed_when: False
    
    - name: etc config - Delete unmanaged files
      file: path="{{ item }}" state=absent
      with_items: "{{ exist_files.stdout_lines }}"
      when:
        - item not in managed_files
    
    0 讨论(0)
提交回复
热议问题