我正在尝试按照以下代码示例中的“名称”字段正确排序列表:
---
- hosts: localhost
vars:
hosts:
- name: host2
uptime: 1d
- name: host10
uptime: 45d
- name: host1
uptime: 3m
tasks:
- name: version sort host list
debug:
#var: hosts | community.general.version_sort
#var: hosts | dictsort(false, 'value')
var: hosts | sort(attribute='name')
如您所见,它没有正确排序主机名(host2 应该排在 host10 之前)。我查了一下 version_sort 过滤器,但它不支持按属性排序。我知道如果主机名正确填充,就不会出现这种情况。但事实就是如此。我搜索了一下,没有看到有人问这个问题。还有其他建议吗?
TASK [version sort host list] *************************************
ok: [localhost] => {
"hosts | sort(attribute='name')": [
{
"name": "host1",
"uptime": "3m"
},
{
"name": "host10", <-------
"uptime": "45d"
},
{
"name": "host2",
"uptime": "1d"
}
]
}
概括:
感谢@Vladimir Botka提供的所有选项!我整合了第三个选项,并制定了以下方案。注意,我更新了字典列表,使其在使用fqdn时稍微复杂一些。但这个方案确实有效:
- hosts: localhost
vars:
hosts:
- {name: host2.example.com, uptime: 1d}
- {name: host10.example.com, uptime: 45d}
- {name: host1.example.com, uptime: 3m}
- {name: host3.example.com, uptime: 3m}
- {name: host15.example.com, uptime: 45d}
- {name: host20.example.com, uptime: 45d}
tasks:
# - debug:
# msg:
# - "index: {{ hosts | map(attribute='name') | community.general.version_sort }}"
# - "host_indexed: {{ dict(hosts|json_query('[].[name,@]')) }}"
# - "solution: {{ (hosts | map(attribute='name') | community.general.version_sort) | map('extract', dict(hosts|json_query('[].[name,@]'))) }}"
- debug:
var: (hosts | map(attribute='name') | community.general.version_sort) | map('extract', dict(hosts|json_query('[].[name,@]')))
结果如下:
PLAY [localhost] *****************************************************************************************************************************************
TASK [Gathering Facts] ***********************************************************************************************************************************
ok: [localhost]
TASK [debug] *********************************************************************************************************************************************
[WARNING]: Collection community.general does not support Ansible version 2.14.17
ok: [localhost] => {
"(hosts | map(attribute='name') | community.general.version_sort) | map('extract', dict(hosts|json_query('[].[name,@]')))": [
{
"name": "host1.example.com",
"uptime": "3m"
},
{
"name": "host2.example.com",
"uptime": "1d"
},
{
"name": "host3.example.com",
"uptime": "3m"
},
{
"name": "host10.example.com",
"uptime": "45d"
},
{
"name": "host15.example.com",
"uptime": "45d"
},
{
"name": "host20.example.com",
"uptime": "45d"
}
]
}
PLAY RECAP ***********************************************************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0