Ansible 刪除多個文件或目錄

 

翻譯和轉載該網頁內容 http://www.mydailytutorials.com/ansible-delete-multiple-files-directories-ansible/python

背景

ansible 有多種方式刪除一個文件或目錄,刪除一個目錄中的全部文件,使用正則表達式刪除文件等等。最安全的方式是使用ansible內置的file模塊。固然你也可使用shell 模塊去實現。但它不是冪等的,所以從新執行會拋出錯誤。linux

刪除一個文件

- name: Ansible delete file example
  file:
    path: /etc/delete.conf
    state: absent

注意:當你知道一個文件名的時候,能夠這樣刪除這個文件。正則表達式

刪除多個文件

- name: Ansible delete multiple file example
  file:
    path: "{{ item }}"
    state: absent
  with_items:
    - hello1.txt
    - hello2.txt
    - hello3.txt

注意:當你知道多個文件名的時候,能夠這樣刪除這些文件。shell

刪除一個目錄或文件夾

- name: Ansible delete directory example
  file:
    path: removed_files
    state: absent

上面這個例子講刪除指定的目錄,若是這個目錄不存在,不會拋出錯誤。npm

使用shell 腳本刪除多個文件

- name: Ansible delete file wildcard example
  shell: rm -rf hello*.txt

上面這個例子講刪除指定的目錄,若是這個目錄不存在,不會拋出錯誤。安全

使用find和file模塊結合linux shell模糊搜索刪除文件

- 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 }}"

使用find和file模塊結合python的正則表達式刪除文件

- hosts: all
  tasks:
  - name: Ansible delete file wildcard
    find:
      paths: /etc/wild_card/example
      patterns: "^he.*.txt"
      use:regex: true
    register: wildcard_files_to_delete

  - name: Ansible remove file wildcard
    file:
      path: "{{ item.path }}"
      state: absent
    with_items: "{{ wildcard_files_to_delete.files }}"

移除晚於某個日期的文件

- hosts: all
  tasks:
  - name: Ansible delete files older than 5 days example
    find:
      paths: /Users/dnpmacpro/Documents/Ansible
      age: 5d
    register: files_to_delete

  - name: Ansible remove files older than a date example
    file:
      path: "{{ item.path }}"
      state: absent
    with_items: "{{ files_to_delete.files }}"
相關文章
相關標籤/搜索