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

Ansible无法从嵌套列表获取memberof_group值求助

解决Ansible中IPA用户组查询报错问题

问题分析

报错提示'dict object' has no attribute 'memberof_group',核心原因有三种可能:要么部分用户的返回结果确实不存在该字段,要么字段名与IPA实际返回的不匹配,要么遍历逻辑未处理空值场景。另外发现请求头里的Accept字段存在拼写错误(applicaton应为application),可能影响返回格式的解析。

解决方案

步骤1:修正请求头拼写错误

先修复uri任务中的Accept头,消除潜在的格式解析问题:

- name: FETCH | IPA | Getting HPC user information
  ansible.builtin.uri:
    url: "https://ipa.example.com/ipa/json" 
    method: POST
    ca_path: ipa.ca.cert
    body: |
      {
        "method": "user_find",
        "params": [
          [
            "{{ item | default('') }}"
          ],
          {
            "all": "true",
            "version": "2.248"
          }
        ],
        "id": 0
      }
    body_format: json
    validate_certs: false
    use_gssapi: true
    url_username: admin
    url_password: password
    timeout: 180 
    headers:
      referer: "https://ipa.example.com/ipa"
      Content-Type: "application/json"
      Accept: "application/json; charset=UTF-8"  # 修正拼写错误
  loop: "{{ __USER_LOGINS }}"
  register: __user_find

步骤2:排查返回数据结构

添加debug任务,确认每个用户返回的具体数据结构,验证目标字段是否存在:

- name: Debug user result structure
  debug:
    var: item.json.result.result
  loop: "{{ __user_find.results }}"

执行后查看输出,确认字段名是否正确(部分IPA版本返回的组字段可能是memberof而非memberof_group)。

步骤3:健壮的组信息提取逻辑

根据实际返回结构,选择以下两种方式之一提取组信息:

方式A:直接处理memberof_group字段(兼容空值)

如果确认字段名是memberof_group,用default过滤器避免空值导致的任务失败:

- name: Get User's groups
  debug:
    msg: |
      {% for result in __user_find.results %}
      {% set user_entry = result.json.result.result | first | default({}) %}
      {{ user_entry.memberof_group | default([]) }}
      {% endfor %}

方式B:解析memberof字段(IPA返回DN格式场景)

如果IPA返回的是memberof字段(内容为组的DN,如cn=ipausers,cn=groups,dc=example,dc=com),通过正则提取组名:

- name: Get User's groups
  debug:
    msg: |
      {% for result in __user_find.results %}
      {% set user_entry = result.json.result.result | first | default({}) %}
      {% set group_dns = user_entry.memberof | default([]) %}
      {% set group_names = group_dns | map('regex_replace', '^cn=([^,]+),.*$', '\1') | list %}
      {{ group_names }}
      {% endfor %}

说明

  • 优先通过debug确认返回结构,确保字段名完全匹配;
  • 始终用default过滤器处理空值或不存在的字段,避免任务中断;
  • 修正请求头拼写错误是基础,保证返回格式能被正确解析。

内容的提问来源于stack exchange,提问作者ij ijere

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 16:04:59