【问题标题】:Get values of different iteration - Jinja2获取不同迭代的值 - Jinja2
【发布时间】:2016-12-23 12:44:24
【问题描述】:

我在 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 列表中收集的,该列表来自一个具有 2 次迭代的 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": []
    }
}

我对@9​​87654325@ 感兴趣,因为这是我需要在模板中获取的值。 模板的结果是这样的:

  {
   "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"

正如您所见,这两个项目的值都是 62316,如果它只是一次迭代就好了,但我需要传递第二次迭代值到第二个扇区。

我该怎么做?

【问题讨论】:

  • 您的 JSON 没有您引用的密钥 results,而是有语法错误 - 在"ip": "2", 中留下逗号,您发布一个完整、连贯且可验证的示例怎么样?如果你不关心它,别人为什么要关心它?

标签: python json ansible jinja2


【解决方案1】:

尝试:

% 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 %}

【讨论】:

  • 嗨@Stijn Diependaele,如果我使用你的解决方案,我会收到下一个错误:"msg": "AnsibleUndefinedVariable: 'dict object' has no attribute 'stdout'"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多