ansible刪除目錄下全部內容

使用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
html

相關文章
相關標籤/搜索