Ansible 刪除多個文件或目錄


 

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

背景

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

刪除一個文件

- 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

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

刪除一個目錄或文件夾

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

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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM