首页 > 解决方案 > 如何使用ansible删除最旧的目录

问题描述

如何使用 ansible 删除最旧的目录。假设我有以下树结构

Parent Directory
 -Dir2020-05-20
 -Dir2020-05-21
 -Dir2020-05-22
 -Dir2020-05-23

现在每次运行 ansible playbook 时,它都应该删除最旧的目录,例如,如果我们认为它的创建日期是 2020-05-20,它应该在第一次运行时删除 Dir2020-05-20。文件模块的年龄属性没有帮助,因为我必须非常随机地运行这个剧本,我想保持有限的没有。这些目录。

标签: ansible

解决方案


考虑到推荐的做法是尽可能不要使用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- 使用它的返回值 matchedwhen: found_dirs.matched > 3使用count过滤器。我更喜欢后一种方法,因为我只是在很多其他情况下使用这个过滤器,所以这只是一种习惯。

供您参考,ansible 有一大堆有用的过滤器(例如,我用过countsort这里,但有几十个)。不需要记住这些过滤器名称,当然,只需记住它们存在并且在许多情况下可能有用。


推荐阅读