如何从ansible中的api响应中提取嵌套值

时间:2018-03-08 07:04:13

标签: api debugging ansible citrix msg

我正在编写一个简单的ansible(v2.5)剧本,它在Citrix netscaler上调用NITRO API并获得200响应(这是针对库存的每个设备):

{ "errorcode": 0, "message": "Done", "severity": "NONE", "vrid": [ { "id": "32", "state": "1", "ifaces": "LA\/2 " }, { "id": "65", "state": "0" }, { "id": "80", "state": "1", "ifaces": "LA\/1 " } ] }

我正在一个名为" citrix_result"的变量中注册此响应。在我的剧本中。

我正在尝试使用调试消息以某种人性化格式输出报告,最好是csv,以便轻松复制/粘贴到Excel中。

我真正需要的是循环遍历每个" id"在citrix_results 200响应中产生类似这样的东西(主机名会在多个vrid的情况下重复,如上面的响应中那样):

...
inventory_hostname1,id1 value,state1 value,ifaces1 value
inventory_hostname1,id2 value,state2 value
inventory_hostname1,id3 value,state3 value,ifaces3 value
...

如果我将此响应提取到Python列表和dicts中,这将很简单。但不幸的是,我在一家严格的Ansible商店工作,需要通过ansible(我显然有点新鲜)这样做。

此外,这个ansible playbook正在通​​过Jenny自动化从GitHub仓库运行,所以我无法真正将这个playbook包装在python脚本中,以便以后进一步操作或后处理200响应。它需要是vanilla ansible / jinja2,并且格式简单,可以从ansible执行输出中轻松复制。

这是完整的剧本,截至今天(包括以下一些解决方案):

- hosts: all
  gather_facts: false
  vars:
    attributes:
      id: id
      state: state
      ifaces: ifaces
  tasks:

  - name: query_vrID_via_nitro_api
    delegate_to: localhost
    ignore_errors: true
    uri:
      url: "http://{{ nsip }}/nitro/v1/config/vrid?attrs={{ attributes.id }},{{ attributes.state }},{{ attributes.ifaces }}"
      method: GET
      status_code: 200
      return_content: yes
      headers:
        X-NITRO-USER: "{{ nitro_user }}"
        X-NITRO-PASS: "{{ nitro_pass }}"
    register: citrix_result

- hosts: localhost
  connection: local
  tasks:
    - shell: cat 'api.json'
      register: result

    - debug: var=result

    - set_fact: myvar="{{ result.stdout | from_json }}"

    - name: create_output_file
      template:
        src: results.j2
        dest: ./files/report.csv

1 个答案:

答案 0 :(得分:1)

- hosts: localhost
  connection: local
  tasks:
    - name: create_output_file
      template:
        src: results.j2
        dest: ./files/report.csv

jinja模板:

inventory_hostname,id,state,ifaces
{% for host in groups['all'] %}
{% set output=hostvars[host]['citrix_result']['stdout'] | from_json %}
{% for item in output['vrid'] %}

{{ host }},{{ item.id }},{{ item.state }}{% if item.ifaces is defined %},{{ item.ifaces }}{% endif %}{% endfor %}
{% endfor %}

报告:

inventory_hostname,id,state,ifaces

52.90.34.153,32,1,LA/2 
52.90.34.153,65,0
52.90.34.153,80,1,LA/1 
34.230.61.32,32,1,LA/2 
34.230.61.32,65,0
34.230.61.32,80,1,LA/1