아래 코드는 웹 디렉토리에 들어가는 첫 번째 파일 만 삭제합니다. 웹 디렉토리 내부의 모든 파일과 폴더를 제거하고 웹 디렉토리를 유지하고 싶습니다. 어떻게해야합니까?
- name: remove web dir contents
file: path='/home/mydata/web/{{ item }}' state=absent
with_fileglob:
- /home/mydata/web/*
참고 : rm -rf
command와 shell을 사용해 보았지만 작동하지 않습니다. 아마도 나는 그들을 잘못 사용하고 있습니다.
올바른 방향으로 도움을 주시면 감사하겠습니다.
ansible 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 = True
ansible.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
}}
답변
나는 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/
답변
아래 명령을 시도하면 작동합니다.
- shell: ls -1 /some/dir
register: contents
- file: path=/some/dir/{{ item }} state=absent
with_items: {{ contents.stdout_lines }}
답변
모든 의견과 제안을 통해 전반적인 재조정 및 오류 방지 구현을 만들었습니다.
# 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
답변
파일 글로브를 사용하면 작동합니다. 게시 한 코드에 구문 오류가 있습니다. 나는 이것이 작동하도록 수정하고 테스트했다.
- name: remove web dir contents
file:
path: "{{ item }}"
state: absent
with_fileglob:
- "/home/mydata/web/*"
