服务器 
首页 > 服务器 > 浏览文章

ansible删除目录下所有内容的方法

(编辑:jimmy 日期: 2024/9/24 浏览:3 次 )

使用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"_blank" href="https://docs.ansible.com/ansible/latest/modules/shell_module.html" rel="external nofollow" >https://docs.ansible.com/ansible/latest/modules/shell_module.html?highlight=shell

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:Windows Server 2016 AD服务器搭建的步骤(图文)
下一篇:windows server 2016部署服务的方法步骤(图文教程)
一句话新闻
一文看懂荣耀MagicBook Pro 16
荣耀猎人回归!七大亮点看懂不只是轻薄本,更是游戏本的MagicBook Pro 16.
人们对于笔记本电脑有一个固有印象:要么轻薄但性能一般,要么性能强劲但笨重臃肿。然而,今年荣耀新推出的MagicBook Pro 16刷新了人们的认知——发布会上,荣耀宣布猎人游戏本正式回归,称其继承了荣耀 HUNTER 基因,并自信地为其打出“轻薄本,更是游戏本”的口号。
众所周知,寻求轻薄本的用户普遍更看重便携性、外观造型、静谧性和打字办公等用机体验,而寻求游戏本的用户则普遍更看重硬件配置、性能释放等硬核指标。把两个看似难以相干的产品融合到一起,我们不禁对它产生了强烈的好奇:作为代表荣耀猎人游戏本的跨界新物种,它究竟做了哪些平衡以兼顾不同人群的各类需求呢?