获取不同迭代的值 - Jinja2

时间:2016-12-23 12:44:24

标签: python json ansible jinja2

我在jinja中有这个模板:

{% for value in id_ip.results %}
    {
       "title": "asd",
       "rel":"adas",
       "type":"application/nalip+json",
       "href": "https://www.api.com:443/api/{{item.item.stdout}}/{{item.stdout}}"
    }{% if loop.last %},{% endif %}
    {% endfor %}

变量是从JSON列表中收集的,来自一个有两次迭代的ansible任务:

- name: Define templatesssss
  template:
      src: requestpayload.j2
      dest: /tmp/requestpayload.j2
      owner: root
      group: root
      mode: 0644
   with_items:
      - "{{id_ip.results}}"

id_ip.results有两次这个JSON的迭代。

  "invocation": {
        "module_args": {
            "var": "item"
        },
        "module_name": "debug"
    },
    "item": {
        "changed": true,
        "invocation": {
            "module_args": {
            "warn": true
            },
            "module_name": "command"
        },
        "item": {
            "changed": true,
            "invocation": {
                "module_args": {
                    "warn": true
                },
                "module_name": "command"
            },
            "item": {
                "gateway": "1",
                "ip": "2"
            },
            "stdout": "62",
            "stdout_lines": [
                "62"
            ],
            "warnings": []
        },
        "stdout": "316",
        "stdout_lines": [
            "316"
        ],
        "warnings": []
    }
}

我对stdout's感兴趣,因为我需要在模板中获取值。 模板的结果如下:

  {
   "title": "asd",
   "rel":"adas",
   "type":"application/vnd.externalip+json",
   "href": "https://servicios.com:443/api/limits/2/externalnetworks/62/ips/316"
}        {
   "title": "asd",
   "rel":"adas",
   "type":"application/vnd.externalip+json",
   "href": "https://servicios.com:443/api/limits/2/externalnetworks/62/ips/316"

正如您可以看到两个项目中的值 62 316 ,如果它只是一次迭代但我需要传递第二个迭代值,那就没问题第二部门。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

尝试:

% for value in id_ip.results %}
    {
       "title": "asd",
       "rel":"adas",
       "type":"application/nalip+json",
       "href": "https://www.api.com:443/api/{{value.item.item.stdout}}/{{value.item.stdout}}"
    }{% if loop.last %},{% endif %}
    {% endfor %}