ansible - padding/ljust 使用 ansible 模板和 jinja

标签 ansible jinja2 ansible-template

我正在寻找一种使用此字典在 ansible 中创建模板的方法。

data= {
  "_dictionary": {
    "keyone": "abc",
    "rtv 4": "data2",
    "longtexthere": "1",
    "keythree": "data3",
    "keyfour": "data1234",
  }
}

模板输出应采用以下格式:

 keyone          abc
 keytwo          data2
 longtexthere    1
 keythree        data3
 keyfour         data1234

使用 python,我可以使用以下命令创建它:

w = max([len(x) for x in data['_dictionary'].keys()])
for k,v in data['_dictionary'].items():
    print('    ', k.ljust(w), '  ', v)

但我无法在 ansible 的 jinja2 模板中创建它。我还没有找到 ljust 的替代品。

目前我的模板是这样的,但我得到的输出没有格式。

{% for key, value in data['_dictionary'].items() %}
    {{ "%s\t%s" | format( key, value ) }}
{% endfor %}

有什么想法、建议吗?

最佳答案

例如

    - debug:
        msg: |
          {% for k,v in data['_dictionary'].items() %}
          {{ "{:<15} {}".format(k, v) }}
          {% endfor %}

给出

  msg: |-
    keyone          abc
    rtv 4           data2
    longtexthere    1
    keythree        data3
    keyfour         data1234

参见formatFormat String Syntax .


问:动态创建格式。

A:比如找到字典中最长的key。在第一列的长度上再添加 1 个空格。以同样的方式计算第二列的长度并在单独的变量中创建格式字符串

    - debug:
        msg: |
          {% for k,v in data['_dictionary'].items() %}
          {{ fmt.format(k, v) }} # comment
          {% endfor %}
      vars:
        col1: "{{ data._dictionary.keys()|map('length')|max + 1 }}"
        col2: "{{ data._dictionary.values()|map('length')|max + 1 }}"
        fmt: "{:<{{ col1 }}} {:<{{ col2 }}}"

给出

  msg: |-
    keyone        abc       # comment
    rtv 4         data2     # comment
    longtexthere  1         # comment
    keythree      data3     # comment
    keyfour       data1234  # comment

关于ansible - padding/ljust 使用 ansible 模板和 jinja,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69426921/

相关文章:

linux - 在两台机器之间引用私有(private) SSH key

regex - 有没有办法使用正则表达式来匹配 ansible 中的主机?

python - 显示模板中存储为二进制 blob 的图像

Ansible with_dict 模板使用

python - 处理多个子元素的最有效方法是什么?

amazon-web-services - 认证或权限失败,对远程目录没有权限

Salt:我可以在命令行中使用参数作为Jinja变量吗?

html - 在同一文件中对大量相似的 HTML 元素使用分页?

python - ansible 条件模板

Ansible 任务 - 如何循环所有预定义的变量以这种格式创建 Linux 组?