我将以下任务结果注册到"output“变量
TASK [bgp status] ****************************************************************************************************************************************************************************
ok: [4.4.4.4] => {
    "msg": [
        {
            "bgp_state": "Established",
            "neighbor": "1.1.1.1",
        },
        {
            "bgp_state": "Down",
            "neighbor": "2.2.2.2",
        },
        {
            "bgp_state": "Established",
            "neighbor": "3.3.3.3",
        }
    ]
}我的debus任务是这样的:
- name: bgp status
     debug:
       msg:
            - "{% if output.msg[0].bgp_state == Established %}{{output.msg[0].neighbor}} BGP IS UP{% elif %}{{output.msg[0].neighbor}}BGP IS DOWN{%- endif %}"
            - "{% if output.msg[1].bgp_state == Established %}{{output.msg[1].neighbor}}BGP IS UP{% elif %}{{output.msg[1].neighbor}}BGP IS DOWN{%- endif %}"
            - "{% if output.msg[2].bgp_state == Established %}{{output.msg[2].neighbor}}BGP IS UP{% elif %}{{output.msg[2].neighbor}}BGP IS DOWN{%- endif %}"错误:
fatal: [4.4.4.4]: FAILED! => {"msg": "template error while templating string: Expected an expression, got 'end of statement block'. String: {% if output.msg[0].bgp_state == Established %}{{output.msg[0].neighbor}}BGP IS UP{% elif %}{{output.msg[0].neighbor}}BGP IS DOWN{%- endif %}"}我知道我做错了,但不确定我的调试任务中的错误在哪里?
预期输出:
1.1.1.1 BGP IS UP
2.2.2.2 BGP IS DOWN
3.3.3.3 BGP IS UP发布于 2021-03-02 03:33:02
你已经写了:
{% elif %}{{output.msg[0].neighbor}}BGP IS DOWN{%- endif %}但我想你的意思是
..。
需要条件表达式,就像
..。此外,还需要将字符串值用引号引起来。
表达式。
解决这两个问题,我们得到:
- name: bgp status
     debug:
       msg:
         - '{% if output.msg[0].bgp_state == "Established" %}{{output.msg[0].neighbor}} BGP IS UP{% else %}{{ output.msg[0].neighbor }} BGP IS DOWN{%- endif %}'
         - '{% if output.msg[1].bgp_state == "Established" %}{{output.msg[1].neighbor}} BGP IS UP{% else %}{{ output.msg[1].neighbor }} BGP IS DOWN{%- endif %}'
         - '{% if output.msg[2].bgp_state == "Established" %}{{output.msg[2].neighbor}} BGP IS UP{% else %}{{ output.msg[2].neighbor }} BGP IS DOWN{%- endif %}'给定示例输入,将生成以下结果:
TASK [bgp status] ****************************************************************************
ok: [localhost] => {
    "msg": [
        "1.1.1.1 BGP IS UP",
        "2.2.2.2 BGP IS DOWN",
        "3.3.3.3 BGP IS UP"
    ]
}如果我在写这篇文章,我可能会重新格式化以获得更好的可读性,并将任务放在循环中:
- name: bgp status
      debug:
        msg:
          - >-
            {% if item.bgp_state == "Established" %}
            {{item.neighbor}} BGP IS UP
            {% else %}
            {{ item.neighbor }} BGP IS DOWN
            {%- endif %}
      loop: "{{ output.msg }}"https://stackoverflow.com/questions/66428361
复制相似问题