ansible - 如何使用ansible删除最旧的目录
问题描述
如何使用 ansible 删除最旧的目录。假设我有以下树结构
Parent Directory
-Dir2020-05-20
-Dir2020-05-21
-Dir2020-05-22
-Dir2020-05-23
现在每次运行 ansible playbook 时,它都应该删除最旧的目录,例如,如果我们认为它的创建日期是 2020-05-20,它应该在第一次运行时删除 Dir2020-05-20。文件模块的年龄属性没有帮助,因为我必须非常随机地运行这个剧本,我想保持有限的没有。这些目录。
解决方案
考虑到推荐的做法是尽可能不要使用shell
或模块,我建议针对这种情况使用纯 ansible 解决方案:command
- name: Get directory list
find:
paths: "{{ target_directory }}"
file_type: directory
register: found_dirs
- name: Get the oldest dir
set_fact:
oldest_dir: "{{ found_dirs.files | sort(attribute='mtime') | first }}"
- name: Delete oldest dir
file:
state: absent
path: "{{ oldest_dir.path }}"
when:
- found_dirs.files | count > 3
有两种方法可以知道使用模块找到了多少文件find
- 使用它的返回值 matched
或when: found_dirs.matched > 3
使用count
过滤器。我更喜欢后一种方法,因为我只是在很多其他情况下使用这个过滤器,所以这只是一种习惯。
供您参考,ansible 有一大堆有用的过滤器(例如,我用过count
和sort
这里,但有几十个)。不需要记住这些过滤器名称,当然,只需记住它们存在并且在许多情况下可能有用。
推荐阅读
- ios - 如何使用 Realm swift 在本地设备上存储资产?
- html - 中心内容被 :before 推到一边
- javascript - JavaScript:在 setTimeout 中定义全局变量
- sql-server - 为什么索引会导致这么多未使用的磁盘空间?
- docker - 在 node-RED 中将子流转换为模块
- google-apps-script - 如何使用 AppScript 在 BigQuery 中将 Google 工作表持久化为表格
- c# - 如何使用列标题动态识别列索引c#
- android - 为什么反应原生 Firebase 通知会转到静默通知部分?
- sql - Snowflake : REGEXP replace with uppercase of capture group
- python - 如何为任意数量的任意键/值对键入提示/类型检查字典(在运行时)?