使用Jinja2模板创建字符串 [英] Create a string using Jinja2 template
问题描述
我要转换此变量:
default_attr:
attr1 :
- "1"
nexatt :
- "b"
...
使用Jinja模板
转换为"attr = 1,nextattr = 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"}
是否可以使用Jinja构造此字符串?
Is there a way to construct this string using Jinja?
推荐答案
这有点肮脏,但是为了回答这个问题,下面的代码片段应该可以满足您的描述.一个问题是您没有指定attr1
或任何其他attr
列表中有多个项目时将发生的情况.如果每个列表中只有一个项目,则此代码段将起作用.
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
这篇关于使用Jinja2模板创建字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!