Create a string using Jinja2 template

倾然丶 夕夏残阳落幕 提交于 2019-12-13 02:49:23

问题


I want to convert this variable:

default_attr:
    attr1    :
    - "1"
    nexatt  :
    - "b"
 ...

to "attr=1,nextattr=b,..." (i.e.comma separated string) using Jinja template. Is there a possible way to do this?

- name: Reading the attributes
  set_fact:
    app_attributes: |
        {% set attributes = " " -%}
        {% for key in default_attr.keys() -%}
           {% for value in default_attr[key] -%}
               {% attributes: "{{ attributes }} + [{'key=value'}]" -%}
           {%- endfor %}
        {%- endfor %}
        {{ attributes }}

The error I get is shown below:

fatal: [dev1]: FAILED! => {"msg": "template error while templating string: Encountered unknown tag 'attributes'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'.. String: {% set attributes = \" \" -%}\n{% for key in default_attr.keys() -%}\n   {% for value in default_attr[key] -%}\n       {% attributes: \"{{ attributes }} + [{'key=value'}]\" -%}\n   {%- endfor %}\n{%- endfor %}\n{{ attributes }}\n"}

Is there a way to construct this string using Jinja?


回答1:


Its a bit dirty way but for the sake of answer the snippet below should work for what you have described. One problem is that you have not specified that what will happen when there are more than one items in attr1 or any other attr list. This snippet will work if there is only one item in each list.

- set_fact:
    default_attr:
        attr1    :
        - "1"
        nexatt  :
        - "b"
- set_fact: app_attributes="{{ default_attr | to_json | regex_replace('\:\ ','=') | regex_replace('[\[\]{}\"]') }}"
- debug: var=app_attributes


来源:https://stackoverflow.com/questions/53220761/create-a-string-using-jinja2-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!