Search code examples
ansiblejinja2

Create a string using Jinja2 template


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?


Solution

  • 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