Ansible 2.9.27中selectattr无法提取字典属性问题求助
问题排查:Ansible调试中selectattr返回空列表
问题场景
在Red Hat Linux 7.9环境运行Ansible 2.9.27,Playbook中编写了两段调试代码:
- name: DEBUG THIS THING1 debug: msg: "FOUND HOME: {{ found_service_accounts['svclinux']['home'] }}" - name: DEBUG THIS THING2 debug: msg: "FOUND: {{ found_service_accounts['svclinux']['home'] | selectattr('path', 'defined') | list }}"
执行后输出:
TASK [service_accounts : DEBUG THIS THING1] *************************************************************************** ok: [myhost.example.com] => { "msg": "FOUND HOME: {u'owner': u'svclinux', u'path': u'/home/svclinux', u'group': u'svc-linux', u'permissions': u'755'}" } TASK [service_accounts : DEBUG THIS THING2] *************************************************************************** ok: [myhost.example.com] => { "msg": "FOUND: []" }
其中found_service_accounts通过set_fact定义,service_account_names为['svclinux']:
- name: set found_service_accounts set_fact: found_service_accounts: | {% set j2fsa = { } %} {%- for user in service_account_names -%} {% set _ = j2fsa.update( { user : { 'home' : { 'path' : homes.results[loop.index0].stdout_lines[0], 'owner' : homes.results[loop.index0].stdout_lines[1], 'group' : homes.results[loop.index0].stdout_lines[2], 'permissions' : homes.results[loop.index0].stdout_lines[3] }, 'ssh_subdirectory' : { 'owner' : ssh_subdir.results[loop.index0].stdout_lines[0], 'permissions' : ssh_subdir.results[loop.index0].stdout_lines[1] } } }) %} {%- endfor %} {{ j2fsa }}
错误原因
selectattr过滤器的作用是从列表中筛选出符合属性条件的元素,但found_service_accounts['svclinux']['home']是一个单一字典对象,不是列表。当对非列表对象使用selectattr时,它会将对象视为长度为0的迭代器,最终返回空列表[]。
解决方法
如果要获取home字典中的path属性,直接访问即可:
- name: DEBUG THIS THING2 debug: msg: "FOUND PATH: {{ found_service_accounts['svclinux']['home'].path }}" # 也可使用索引方式:{{ found_service_accounts['svclinux']['home']['path'] }}
如果需要检查path属性是否存在,可用default过滤器做容错处理:
- name: DEBUG THIS THING2 debug: msg: "FOUND PATH: {{ found_service_accounts['svclinux']['home'].path | default('Path not defined') }}"
若后续需求是处理列表型的home数据,需先确保found_service_accounts['svclinux']['home']为列表结构,再使用selectattr。
内容的提问来源于stack exchange,提问作者Mike S
相关产品推荐
相关产品推荐

