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

如何从Ansible URI模块返回结果中提取management-ip与hostname

解决方案

你的问题出在字段引用路径错误:managementAddress和mcpDeviceName并非直接位于mgmtip.json层级下,而是嵌套在mgmtip.json.items数组的每一个元素中。以下是几种可行的提取方法:

1. 提取所有目标字段到独立列表

提取所有管理IP地址

- name: 提取所有管理IP地址到列表
  set_fact:
    management_addresses: "{{ mgmtip.json.items | map(attribute='managementAddress') | list }}"

- name: 显示管理IP列表
  debug:
    var: management_addresses

提取所有设备名称

- name: 提取所有设备名称到列表
  set_fact:
    device_names: "{{ mgmtip.json.items | map(attribute='mcpDeviceName') | list }}"

- name: 显示设备名称列表
  debug:
    var: device_names

2. 创建IP与设备名称的映射字典

如果需要将IP地址和对应的设备名关联起来,可生成键值对字典:

- name: 创建IP-设备名映射字典
  set_fact:
    device_ip_map: "{{ dict(mgmtip.json.items | json_query('[].[managementAddress, mcpDeviceName]')) }}"

- name: 显示IP-设备名映射
  debug:
    var: device_ip_map

3. 遍历设备逐个处理字段

若需对每个设备单独操作,可通过loop遍历items数组:

- name: 遍历设备并输出对应字段
  debug:
    msg: "设备名称: {{ item.mcpDeviceName }}, 管理IP: {{ item.managementAddress }}"
  loop: "{{ mgmtip.json.items }}"

额外优化建议

你的uri模块配置存在两处可优化点:

  • GET请求通常无需body参数,可移除body: '{"include": "none"}'(若接口无强制要求)
  • return_content: yes是uri模块的顶层参数,而非headers内的属性,需调整位置:
---
- name: Step - 1.1 - Find management_ips
  uri:
      url: 'https://{{ ansible_host}}/mgmt/shared/resolver/device-groups/cm-bigip-allBigIpDevices/devices?$select=mcpDeviceName,managementAddress'
      user: "{{ ansible_admin }}"
      password: "{{ ansible_pass }}"
      method: GET
      headers:
        Content-Type: application/json
      return_content: yes
      validate_certs: false
  register: mgmtip

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 03:35:08