使用ansible的同窗都知道,ansible只支持新增刪除具體的某個文件夾或者文件,以下所示:
- 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
- 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文件夾或者緩存文件夾,這個時候就僅僅須要刪除目錄下的全部內容而已。
#先使用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=shellhtml