可以使用Ansible的filter功能来实现对字符串进行非字典排序。其中使用自定义的Python函数可以将包含整数的字符串进行数字排序。
示例代码如下:
- name: Non-lexicographic sorting of strings with integers
hosts: localhost
vars:
string_list:
- foo1
- foo10
- foo5
- foo11
tasks:
- name: Sort the list numerically
set_fact:
sorted_list: "{{ string_list | sort_by('split(" ")[0]') | sort(sorter('foo')) }}"
vars:
- sorter: |-
def sort_func(v):
if v.startswith('foo'):
return int(v[len('foo'):])
return v
return sorted(l, key=sort_func)
- sorted_list: "{{ string_list | sort_by('split(" ")[0]') | sort(sorter) }}"
- debug:
var: sorted_list
在示例中,首先定义了一个包含整数的字符串列表。然后通过set_fact将该列表排序,并使用自定义的Python函数对这些字符串进行数字排序。最后通过debug模块输出排序后的字符串列表。
输出结果如下所示:
ok: [localhost] => {
"sorted_list": [
"foo1",
"foo5",
"foo10",
"foo11"
]
}