使用jinja2获取错误-Ansible调试消息-模板字符串时模板错误:应为表达式,Get end of statement block

使用jinja2获取错误-Ansible调试消息-模板字符串时模板错误:应为表达式,Get end of statement block,ansible,jinja2,Ansible,Jinja2,我将以下任务结果注册到“输出”变量 我的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 %}"

我将以下任务结果注册到“输出”变量

我的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
你写过:

{% elif %}{{output.msg[0].neighbor}}BGP IS DOWN{%- endif %}
但我想你指的是
else
elif
需要一个条件表达式,就像
if
一样。此外,还需要在
if
表达式中引用字符串值

解决这两个问题,我们可以:

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

谢谢你@larsks,现在可以用了。
    - 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 }}"