使用ansible的同學都知道,ansible只支持新增刪除具體的某個文件夾或者文件,如下所示:
1. 創建目錄,刪除整個目錄
- name: Create a directory if it does not exist file: path: /appvol/some_directory state: directory mode: '0755' - name: Remove a directory if it exist file: path: /appvol/some_directory state: absent
2.創建文件,刪除單個文件
- name: Create a file if it does not exist file: path: /appvol/some_directory/hello.txt state: touch mode: '0755' - name: Remove a file if it exist file: path: /appvol/some_directory/hello.txt state: absent
對於某些場景,我們想清空log文件夾或者緩存文件夾,這個時候就僅僅需要刪除目錄下的所有內容而已。
3.刪除某個目錄下的所有文件,或者符合條件的文件名
#先使用shell模塊獲取該目錄下所有文件名,並且存儲到一個變量files_list - name: list the files of dir some_directory shell: ls args: chdir: /appvol/some_directory register: files_list #使用with_items屬性,將files_list變量以lines的形式輸出,再借助file模塊循環刪除每個文件 - name: Remove a directory if it does not exist file: path: /appvol/some_directory/{{ item }} state: absent with_items: - "{{ files_list.stdout_lines }}"
參考ansible官方文檔:
ansible file 模塊參考: refer to https://docs.ansible.com/ansible/latest/modules/file_module.html?highlight=file
ansible shell模塊參數:https://docs.ansible.com/ansible/latest/modules/shell_module.html?highlight=shell