Programing

답변 : 디렉토리 안의 파일과 폴더를 삭제하는 방법?

lottogame 2020. 6. 25. 08:03
반응형

답변 : 디렉토리 안의 파일과 폴더를 삭제하는 방법?


아래 코드는 웹 디렉토리에 들어가는 첫 번째 파일 만 삭제합니다. 웹 디렉토리 내부의 모든 파일과 폴더를 제거하고 웹 디렉토리를 유지하고 싶습니다. 어떻게해야합니까?

  - name: remove web dir contents
     file: path='/home/mydata/web/{{ item }}' state=absent
     with_fileglob:
       - /home/mydata/web/*

참고 : rm -rfcommand와 shell을 사용해 보았지만 작동하지 않습니다. 아마도 내가 잘못 사용하고있을 것입니다.

올바른 방향으로 도움을 주시면 감사하겠습니다.

사용 가능한 2.1.0.0을 사용하고 있습니다.


아래 코드는의 전체 내용을 삭제합니다 artifact_path

- name: Clean artifact path
  file:
    state: absent
    path: "{{ artifact_path }}/"

참고 : 디렉토리도 삭제됩니다.


쉘 모듈 사용 ( 등전위 도) :

- shell: /bin/rm -rf /home/mydata/web/*

생성 날짜 및 소유자 / 권한에 관심이없는 경우 가장 깨끗한 솔루션 :

- file: path=/home/mydata/web state=absent
- file: path=/home/mydata/web state=directory

디렉토리 (기본적으로 https://stackoverflow.com/a/38201611/1695680 의 복사본)를 제거하면 Ansible은이 작업을 rmtree후드 아래에서 수행합니다.

- name: remove files and directories
  file:
    state: "{{ item }}"
    path: "/srv/deleteme/"
    owner: 1000  # set your owner, group, and mode accordingly
    group: 1000
    mode: '0777'
  with_items:
    - absent
    - directory

전체 디렉토리를 제거하고 다시 작성하는 데 어려움이 없다면 파일 및 디렉토리를 스캔하여 하나씩 삭제할 수 있습니다. 어느 정도 시간이 걸립니다. 아마도 [ssh_connection]\npipelining = Trueansible.cfg에 있는지 확인하고 싶을 것 입니다.

- block:
  - name: 'collect files'
    find:
      paths: "/srv/deleteme/"
      hidden: True
      recurse: True
      # file_type: any  # Added in ansible 2.3
    register: collected_files

  - name: 'collect directories'
    find:
      paths: "/srv/deleteme/"
      hidden: True
      recurse: True
      file_type: directory
    register: collected_directories

  - name: remove collected files and directories
    file:
      path: "{{ item.path }}"
      state: absent
    with_items: >
      {{
        collected_files.files
        + collected_directories.files
      }}

아래 명령을 시도하면 작동합니다.

- shell: ls -1 /some/dir
  register: contents

- file: path=/some/dir/{{ item }} state=absent
  with_items: {{ contents.stdout_lines }}

나는 rm 솔루션을 정말로 좋아하지 않았고, 또한 ansible은 rm 사용에 대한 경고를 제공합니다. 따라서 rm이 ​​필요없고 경고가없는 방법입니다.

- hosts: all
  tasks:
  - name: Ansible delete file glob
    find:
      paths: /etc/Ansible
      patterns: "*.txt"
    register: files_to_delete

  - name: Ansible remove file glob
    file:
      path: "{{ item.path }}"
      state: absent
    with_items: "{{ files_to_delete.files }}"

출처 : http://www.mydailytutorials.com/ansible-delete-multiple-files-directories-ansible/


모든 의견과 제안을 통해 전반적인 재조정 및 오류 방지 구현을 만들었습니다.

# collect stats about the dir
- name: check directory exists
  stat:
    path: '{{ directory_path }}'
  register: dir_to_delete

# delete directory if condition is true
- name: purge {{directory_path}}
  file:
    state: absent
    path: '{{ directory_path  }}'
  when: dir_to_delete.stat.exists and dir_to_delete.stat.isdir

# create directory if deleted (or if it didn't exist at all)
- name: create directory again
  file:
    state: directory
    path: '{{ directory_path }}'
  when: dir_to_delete is defined or dir_to_delete.stat.exist == False

파일 glob를 사용하면 작동합니다. 게시 한 코드에 구문 오류가 있습니다. 나는 이것이 작동하도록 수정하고 테스트했다.

- name: remove web dir contents
  file:
    path: "{{ item }}"
    state: absent
  with_fileglob:
    - "/home/mydata/web/*"

Ansible은 여전히 https://github.com/ansible/ansible-modules-core/issues/902 를 구현하기 위해 논쟁 중이지만state = empty

my_folder: "/home/mydata/web/"
empty_path: "/tmp/empty"


- name: "Create empty folder for wiping."
  file:
    path: "{{ empty_path }}" 
    state: directory

- name: "Wipe clean {{ my_folder }} with empty folder hack."
  synchronize:
    mode: push

    #note the backslash here
    src: "{{ empty_path }}/" 

    dest: "{{ nl_code_path }}"
    recursive: yes
    delete: yes
  delegate_to: "{{ inventory_hostname }}"

그러나 동기화를 사용하면 파일을 삭제와 함께 올바르게 동기화 할 수 있어야합니다.


이와 관련하여 열려 있는 문제 가 있습니다 .

지금은 솔루션이 저에게 효과적입니다. 로컬로 빈 폴더를 만들고 원격 폴더와 동기화하십시오.

다음은 샘플 플레이 북입니다.

- name: "Empty directory"
  hosts: *
  tasks:
    - name: "Create an empty directory (locally)"
      local_action:
        module: file
        state: directory
        path: "/tmp/empty"

    - name: Empty remote directory
      synchronize:
        src: /tmp/empty/
        dest: /home/mydata/web/
        delete: yes
        recursive: yes

I want to make sure that the find command only deletes everything inside the directory and leave the directory intact because in my case the directory is a filesystem. The system will generate an error when trying to delete a filesystem but that is not a nice option. Iam using the shell option because that is the only working option I found so far for this question.

What I did:

Edit the hosts file to put in some variables:

[all:vars]
COGNOS_HOME=/tmp/cognos
find=/bin/find

And create a playbook:

- hosts: all
  tasks:
  - name: Ansible remove files
    shell: "{{ find }} {{ COGNOS_HOME }} -xdev -mindepth 1 -delete"

This will delete all files and directories in the COGNOS_HOME variable directory/filesystem. The "-mindepth 1" option makes sure that the current directory will not be touched.


I have written an custom ansible module to cleanup files based on multiple filters like age, timestamp, glob patterns, etc.

It is also compatible with ansible older versions. It can be found here.

Here is an example:

- cleanup_files:
  path_pattern: /tmp/*.log
  state: absent
  excludes:
    - foo*
    - bar*

Just a small cleaner copy & paste template of ThorSummoners answer, if you are using Ansible >= 2.3 (distinction between files and dirs not necessary anymore.)

- name: Collect all fs items inside dir
  find:
    path: "{{ target_directory_path }}"
    hidden: true
    file_type: any
  changed_when: false
  register: collected_fsitems
- name: Remove all fs items inside dir
  file:
    path: "{{ item.path }}"
    state: absent
  with_items: "{{ collected_fsitems.files }}"
  when: collected_fsitems.matched|int != 0

That's what I come up with:

- name: Get directory listing
  find:
    path: "{{ directory }}" 
    file_type: any
    hidden: yes
  register: directory_content_result

- name: Remove directory content
  file:
    path: "{{ item.path }}" 
    state: absent
  with_items: "{{ directory_content_result.files }}" 
  loop_control:
    label: "{{ item.path }}" 

First, we're getting directory listing with find, setting

  • file_type to any, so we wouldn't miss nested directories and links
  • hidden to yes, so we don't skip hidden files
  • also, do not set recurse to yes, since it is not only unnecessary, but may increase execution time.

Then, we go through that list with file module. It's output is a bit verbose, so loop_control.label will help us with limiting output (found this advice here).


그러나 이전 솔루션은 내용을 반복하기 때문에 다소 느리다는 것을 알았습니다.

- name: Get directory stats
  stat:
    path: "{{ directory }}"
  register: directory_stat

- name: Delete directory
  file:
    path: "{{ directory }}"
    state: absent

- name: Create directory
  file:
    path: "{{ directory }}"
    state: directory
    owner: "{{ directory_stat.stat.pw_name }}"
    group: "{{ directory_stat.stat.gr_name }}"
    mode: "{{ directory_stat.stat.mode }}"
  • 로 디렉토리 속성을 가져옵니다 stat
  • 디렉토리 삭제
  • 동일한 특성으로 디렉토리를 다시 작성하십시오.

그것으로 충분했지만 원한다면 추가 할 수도 있습니다 attributes.


항상 Linux에 있다고 가정하면 findcmd를 사용해보십시오 .

- name: Clean everything inside {{ item }}
  shell: test -d {{ item }} && find {{ item }} -path '{{ item }}/*' -prune -exec rm -rf {} \;
  with_items: [/home/mydata/web]

파일 / 폴더 / 숨겨진 /home/mydata/web


先 删除 对应 的 目录, 然后 在 创建 该 目录, 使用 的 是 嵌套 循环
  - name: delete old data and clean cache
    file:
      path: "{{ item[0] }}" 
      state: "{{ item[1] }}"
    with_nested:
      - [ "/data/server/{{ app_name }}/webapps/", "/data/server/{{ app_name }}/work/" ]
      - [ "absent", "directory" ]
    ignore_errors: yes

이것이 나의 예입니다.

  1. 저장소 설치
  2. rsyslog 패키지 설치
  3. rsyslog 중지
  4. / var / log / rsyslog / 내부의 모든 파일을 삭제하십시오.
  5. rsyslog 시작

    - hosts: all
      tasks:
        - name: Install rsyslog-v8 yum repo
          template:
            src: files/rsyslog.repo
            dest: /etc/yum.repos.d/rsyslog.repo
    
        - name: Install rsyslog-v8 package
          yum:
            name: rsyslog
            state: latest
    
        - name: Stop rsyslog
          systemd:
            name: rsyslog
            state: stopped
    
        - name: cleann up /var/spool/rsyslog
          shell: /bin/rm -rf /var/spool/rsyslog/*
    
        - name: Start rsyslog
          systemd:
            name: rsyslog
            state: started
    

아래는 나를 위해 일했습니다.

- name: Ansible delete html directory
  file:
   path: /var/www/html
   state: directory

참고 URL : https://stackoverflow.com/questions/38200732/ansible-how-to-delete-files-and-folders-inside-a-directory

반응형