如何使用 Ansible 过滤树中每个文件的最新版本? [英] How to filter the latest version of every file in a tree using Ansible?
问题描述
我有一个包含各种文件的中等大小的目录树:
I have a mid-sized directory-tree with variety of files:
- /some/place/distfiles/foo-1.2.jar
- /some/place/distfiles/subdir/foo-1.3.jar
- /some/place/distfiles/bar-1.1.jar
- /some/place/distfiles/bar-1.1.2.jar
我使用 find-module 获取完整列表,但我只需要每个 foo 和 bar 的 latest 版本.上面的集合,例如,需要简化为:
I use the find-module to get the full list, but I only need the latest versions for each foo and bar. The above set, for example, needs to be reduced to:
- /some/place/distfiles/subdir/foo-1.3.jar
- /some/place/distfiles/bar-1.1.2.jar
不,我不能依赖文件的时间戳——只能依赖文件名的数字部分...
No, I cannot rely on the files' timestamps -- only on the numerical parts of the filenames...
有人可以建议一种优雅的方法吗?
Can someone suggest an elegant way of doing it?
推荐答案
这将是 jinja2 的一些重要内容,因此您可能更喜欢编写自定义模块,以便您可以使用实际的编程语言工作(您仍然可以使用 find:
和 register:
捕获文件名列表,然后将其提供给您的自定义模块以根据您的规则汇总每个文件的最新")
It will be some non-trivial amount of jinja2, so you may be happier writing a custom module so you can work in an actual programming language (you can still use find:
and register:
to capture the list of filenames, and then give it to your custom module to roll up the "latest" for each file based on your rules)
也就是说,我猜版本
test 可用于在您将项目从其基本名称到其版本号拆分为 tuple[str, str]
后找到最新的:
That said, I would guess the version
test can be used to find the newest after you have split the items into tuple[str, str]
from its basename to its version number:
- find:
paths:
- /some/place/distfiles
# etc
register: my_jars
- set_fact:
versions_by_filename: >-
{%- set results = {} -%}
{%- for f in my_jars.files -%}
{%- set bn = f.path | basename
| regex_replace(ver_regex, '\\1') -%}
{%- set v = f.path | regex_replace(ver_regex, '\\2') -%}
{%- set _ = results.setdefault(bn, []).append(v) -%}
{%- endfor -%}
{{ results }}
vars:
ver_regex: '(.*)-([0-9.-]+)\.jar'
- set_fact:
most_recent: >-
{%- set results = {} -%}
{%- for fn, ver_list in versions_by_filename.items() -%}
{%- set tmp = namespace(latest=ver_list[0]) -%}
{%- for v in ver_list -%}
{%- if tmp.latest is version(v, '<') -%}
{%- set tmp.latest = v -%}
{%- endif -%}
{%- endfor -%}
{%- set _ = results.update({fn: tmp.latest}) -%}
{%- endfor -%}
{{ results }}
这篇关于如何使用 Ansible 过滤树中每个文件的最新版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!