0

这是我的神社模板:

maths.j2
{% set my_list2 = [{"1":"58"},{"2":"20"},{"3":"90"}] -%}

{% set total = 0 | int -%}
{% for parent_dict in my_list2 %}
{% for key, value in parent_dict.items() %}
{% set total = total  +  value  -%}
{% endfor %}
{% endfor %}


total marks obtained  = {{ total }}

我想遍历 my_list2 并需要打印值的总和。像 58+20+90 = 168 所以需要像这样的输出:获得的总分 = 168

我有一本使用这个模板的剧本。但是当我执行剧本时,我得到了错误。

---
  - name: Demonstrating variables in Jinja2 Loops
    hosts: localhost
    connection: local
    gather_facts: no
    tasks:
      - name: Create the Jinja2 based template
        template: src=maths.j2 dest=./output.txt

错误:

[unix@AMITSUNEJA maths]$  ansible-playbook maths.yml

PLAY [Demonstrating variables in Jinja2 Loops] ***********************************************************************

TASK [Create the Jinja2 based template] ******************************************************************************
fatal: [localhost]: FAILED! => {"changed": false, "msg": "AnsibleError: Unexpected templating type error occurred on ({% set my_list2 = [{\"1\":\"58\"},{\"2\":\"20\"},{\"3\":\"90\"}] -%}\n\n{% set total = 0 | int -%}\n{% for parent_dict in my_list2 %}\n{% for key, value in parent_dict.items() %}\n{% set total = total  +  value  -%}\n{% endfor %}\n{% endfor %}\n\n\ntotal marks obtained  = {{ total }}\n\n\n\n\n): unsupported operand type(s) for +: 'int' and 'str'"}

PLAY RECAP ***********************************************************************************************************
localhost                  : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

[unix@AMITSUNEJA maths]$
4

0 回答 0