有没有办法以自然的方式对 Ansible 或 Jinja 中的列表进行排序?
例如,这是列表
test
test123
test12
test5
test1234test
test22te
我需要它来考虑整个数字而不是单个数字,所以test12
在下面test5
等等。
给定列表
l1:
- test
- test123
- test12
- test5
- test1234test
- test22te
创建一个带有属性的列表index整数类型,例如
- set_fact:
l2: "{{ l2|default([]) +
[{'index': (_index|length > 0)|ternary(_index|int, 0),
'name': item}] }}"
loop: "{{ l1 }}"
vars:
_regex: '^test(\d*)\D*$'
_replace: '\1'
_index: "{{ item|regex_replace(_regex, _replace) }}"
- debug:
msg: "{{ l2|sort(attribute='index')|
map(attribute='name')|
list }}"
gives
msg:
- test
- test5
- test12
- test22te
- test123
- test1234test
无需迭代,声明变量
_regex: '^test(\d*)\D*$'
_replace: '\1'
_index: "{{ l1|map('regex_replace', _regex, _replace)|map('int')|list }}"
l2: "{{ dict(_index|zip(l1))|
dict2items|
sort(attribute='key')|
map(attribute='value')|
list }}"
给出相同的结果
l2:
- test
- test5
- test12
- test22te
- test123
- test1234test
用于测试的完整剧本示例
- hosts: localhost
vars:
l1:
- test
- test123
- test12
- test5
- test1234test
- test22te
_regex: '^test(\d*)\D*$'
_replace: '\1'
_index: "{{ l1|map('regex_replace', _regex, _replace)|map('int')|list }}"
l2: "{{ dict(_index|zip(l1))|
dict2items|
sort(attribute='key')|
map(attribute='value')|
list }}"
tasks:
- debug:
var: _index
- debug:
var: l2
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)