You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 04:15:10