【问题标题】:Create a string using Jinja2 template使用 Jinja2 模板创建字符串
【发布时间】:2018-11-09 06:20:23
【问题描述】:

我要转换这个变量:

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

【问题讨论】:

    标签: ansible jinja2


    【解决方案1】:

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

    - 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, ..."。现在应该可以了。也许我首先不需要列表。我试图将此字符串传递给我使用command 模块运行的shell。但只有第一个元素被传递。 -command: "{{ shell }} --option {{ app_attributes }}。但是,只有第一个元素被传递到 shell。这是为什么?因为逗号后面有空格?
    【解决方案2】:

    您可以构建一个键/值对列表,然后根据需要将它们连接起来:

    - hosts: localhost
      connection: local
      gather_facts: no
      vars:
        the_dict:
          My: Dog
          Has: Fleas
      tasks:
        - name: Convert the dict to a list of key=value elements
          ansible.builtin.set_fact:
            kv_list: "{{ kv_list | default([]) | union([[item.key, item.value] | join('=')]) }}"
          loop: "{{ the_dict | dict2items }}"
    
    - name: Print out a comma-separated string 
      ansible.builtin.debug:
        msg: "{{ kv_list | join(',') }}"
    

    这会产生"msg": "My=Dog,Has=Fleas"

    【讨论】:

      猜你喜欢
      • 2019-02-18
      • 2018-07-29
      • 2021-04-01
      • 2017-06-07
      • 2018-08-19
      • 1970-01-01
      • 2014-04-06
      • 2022-12-02
      • 2020-08-20
      相关资源
      最近更新 更多