使用 Jinja2 模板创建一个字符串

使用 Jinja2 模板创建一个字符串

问题描述:

我想转换这个变量:

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