删除列表中两天前创建的所有文件夹。

huangapple go评论66阅读模式
英文:

Delete all the folders that are older than two days from a list of folders

问题

以下是您要的翻译部分:

我有三个文件夹。我需要 Ansible 检查它们并删除两天前的那个(或那些)。

以下是我的任务:

- name: 获取较旧文件的路径
  find:
    paths: "{{ path }}/DB/{{ item }}/"
    age: 2d
    file_type: directory
    recurse: yes
  register: filesolderthan2
  with_items:
    - "{{ bucket }}"

- name: 删除较旧的文件
  file:
    path: item.path
    state: absent
  with_items: "{{ filesolderthan2.results }}"

变量文件:

bucket:
  - test1
  - test2
  - test3
path: "/backup"

我成功获取了路径,但无法删除所有这些文件夹。当我尝试使用:

path: {{ item.path }}

时,我遇到了字典错误。

英文:

I have three folders. I need Ansible to check them and delete the one(s) older than two days.

Those are my tasks:

- name: Get older files path
  find:
    paths: "{{ path }}/DB/{{ item }}/"
    age: 2d
    file_type: directory
    recurse: yes
  register: filesolderthan2
  with_items:
    - "{{ bucket }}"

- name: Remove older files
  file:
    path: item.path
    state: absent
  with_items: "{{ filesolderthan2.results }}"

Variable file

bucket:
  - test1
  - test2
  - test3
path: "/backup"

I did get the path but was not able to delete all those folders.
When I tried to use

path: {{ item.path }}

I get dict error

答案1

得分: 3

The find module will list you all the files matched in a files field of a dictionary.

Since you are registering under a loop, you have a results field on top of those multiple files field.

So, what you can do is to use a couple of map and flatten filters to get all those files:

- name: 移除旧文件
  file:
    path: "{{ item.path }}"
    state: absent
  loop: "{{ filesolderthan2.results | map(attribute='files') | flatten(1) }}"
英文:

The find module will list you all the files matched in a files field of a dictionary.

Since you are registering under a loop, you have a results field on top of those multiple files field.

So, what you can do is to use a couple of map and flatten filters to get all those files:

- name: Remove older files
  file:
    path: "{{ item.path }}"
    state: absent
  loop: "{{ filesolderthan2.results | map(attribute='files') | flatten(1) }}"

huangapple
  • 本文由 发表于 2023年2月27日 10:36:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75576347.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定