使用ansible的同學(xué)都知道,ansible只支持新增刪除具體的某個(gè)文件夾或者文件,如下所示:
1. 創(chuàng)建目錄,刪除整個(gè)目錄
- 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.創(chuàng)建文件,刪除單個(gè)文件
- 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
對(duì)于某些場(chǎng)景,我們想清空l(shuí)og文件夾或者緩存文件夾,這個(gè)時(shí)候就僅僅需要?jiǎng)h除目錄下的所有內(nèi)容而已。
3.刪除某個(gè)目錄下的所有文件,或者符合條件的文件名
#先使用shell模塊獲取該目錄下所有文件名,并且存儲(chǔ)到一個(gè)變量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模塊循環(huán)刪除每個(gè)文件
- 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模塊參數(shù):https://docs.ansible.com/ansible/latest/modules/shell_module.html?highlight=shell
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。