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

如何用Ansible读取FortiGate的JSON响应并输出指定字段

用Ansible提取FortiGate JSON响应及本地JSON文件的指定字段

一、处理FortiGate返回的JSON响应

假设你通过Ansible的fortios_firewall_policy模块获取到FortiGate的防火墙策略数据,返回的JSON结构类似如下:

{
  "ansible_facts": {
    "fortios_firewall_policy": {
      "results": [
        {
          "name": "Allow-HTTP",
          "srcintf": [{"name": "port1"}],
          "dstintf": [{"name": "port2"}],
          "action": "accept"
        },
        {
          "name": "Block-HTTPS",
          "srcintf": [{"name": "port3"}],
          "dstintf": [{"name": "port4"}],
          "action": "deny"
        }
      ]
    }
  }
}

提取指定字段的Playbook示例

用set_fact整理数据,再通过debug输出目标字段:

- name: 获取FortiGate防火墙策略
  fortios_firewall_policy:
    vdom: "root"
    access_token: "your_fortigate_token"
    action: "get"
  register: fg_policies

- name: 提取并整理所需字段
  set_fact:
    filtered_policies: "{{ fg_policies.ansible_facts.fortios_firewall_policy.results | json_query('[].{Name: name, Source_Interface: srcintf[0].name, Destination_Interface: dstintf[0].name}') }}"

- name: 展示提取后的字段
  debug:
    var: filtered_policies

关键说明

  • json_query依赖JMESPath语法,[].{Name: name, ...}表示遍历所有结果,将指定字段重命名后输出。
  • 如果srcintf/dstintf是多接口数组,可改为srcintf[*].name获取所有接口名称,结果会以列表形式返回。

二、读取本地JSON文件并提取字段

完全支持读取本地JSON文件,用lookup插件配合from_json过滤器即可实现:

假设本地JSON文件fg_policies.json结构和API响应一致,Playbook示例:

- name: 读取本地JSON文件
  set_fact:
    local_policy_data: "{{ lookup('file', './fg_policies.json') | from_json }}"

- name: 提取本地JSON中的指定字段
  set_fact:
    local_filtered_policies: "{{ local_policy_data.results | json_query('[].{Name: name, Source_Interface: srcintf[0].name, Destination_Interface: dstintf[0].name}') }}"

- name: 展示本地文件提取结果
  debug:
    var: local_filtered_policies

关键说明

  • lookup('file', './fg_policies.json')读取本地文件内容,from_json将字符串转换为可操作的JSON对象。
  • 后续的json_query用法和处理API响应完全一致,可根据实际JSON结构调整JMESPath表达式。

期望输出示例

执行上述Playbook后,输出会类似:

ok: [localhost] => {
    "filtered_policies": [
        {
            "Destination_Interface": "port2",
            "Name": "Allow-HTTP",
            "Source_Interface": "port1"
        },
        {
            "Destination_Interface": "port4",
            "Name": "Block-HTTPS",
            "Source_Interface": "port3"
        }
    ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:55:17