Ansible 使用Jinja2模板创建字符串

Ansible 使用Jinja2模板创建字符串,ansible,jinja2,Ansible,Jinja2,我要转换此变量: default_attr: attr1 : - "1" nexatt : - "b" ... 使用Jinja模板修改为“attr=1,nextattr=b,…”(即逗号分隔的字符串)。有没有一种可能的方法可以做到这一点 - name: Reading the attributes set_fact: app_attributes: | {% set attributes = " " -%}

我要转换此变量:

default_attr:
    attr1    :
    - "1"
    nexatt  :
    - "b"
 ...
使用Jinja模板修改为“attr=1,nextattr=b,…”(即逗号分隔的字符串)。有没有一种可能的方法可以做到这一点

- 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 }}
我得到的错误如下所示:

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构造这个字符串?

这有点脏,但是为了回答这个问题,下面的代码片段应该适用于您所描述的内容。一个问题是,您没有指定当
attr1
或任何其他
attr
列表中有多个项目时会发生什么情况。如果每个列表中只有一个项目,则此代码段将起作用

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

这有点脏,但为了回答问题,下面的代码片段应该适用于您所描述的内容。一个问题是,您没有指定当
attr1
或任何其他
attr
列表中有多个项目时会发生什么情况。如果每个列表中只有一个项目,则此代码段将起作用

- set_fact:
    default_attr:
        attr1    :
        - "1"
        nexatt  :
        - "b"
- set_fact: app_attributes="{{ default_attr | to_json | regex_replace('\:\ ','=') | regex_replace('[\[\]{}\"]') }}"
- debug: var=app_attributes
嗯,那奏效了。我得到
“attr1=1,nextattr=b,…”
。现在应该可以了。也许我一开始就不需要列表。我正在尝试将这个字符串传递给我使用
命令
模块运行的shell。但只有第一个元素被传递
-command:“{{shell}}--option{{app_attributes}}
。但是,只有第一个元素被传递到shell。这是为什么?因为逗号后面的空格?嗯,这起作用了。我得到
”attr1=1,nextattr=b。。。“
。现在应该可以了。也许我一开始就不需要列表。我正在尝试将这个字符串传递给我使用
命令
模块运行的shell。但只有第一个元素被传递
-command:“{{shell}}--option{{app_attributes}}
。但是,只有第一个元素被传递到shell。这是为什么?因为逗号后面有空格?