I am looking for a way to create a template in ansible with this dictionary.
data= {
"_dictionary": {
"keyone": "abc",
"rtv 4": "data2",
"longtexthere": "1",
"keythree": "data3",
"keyfour": "data1234",
}
}
The template output should have this format:
keyone abc
keytwo data2
longtexthere 1
keythree data3
keyfour data1234
With python I can create it with:
w = max([len(x) for x in data['_dictionary'].keys()])
for k,v in data['_dictionary'].items():
print(' ', k.ljust(w), ' ', v)
But I can't a way to create it in a jinja2 template in ansible. I have not found a replacement for ljust.
Currently my template is this, but I got a output without format.
{% for key, value in data['_dictionary'].items() %}
{{ "%s\t%s" | format( key, value ) }}
{% endfor %}
Any ideas, sugestion?
For example,
- debug:
msg: |
{% for k,v in data['_dictionary'].items() %}
{{ "{:<15} {}".format(k, v) }}
{% endfor %}
gives
msg: |-
keyone abc
rtv 4 data2
longtexthere 1
keythree data3
keyfour data1234
See format and Format String Syntax.
Q: "Create the format dynamically."
A: For example, find the longest key in the dictionary. Add 1 more space to the length of the first column. In the same way, calculate the length of the second column and create the format string in a separate variable
- 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 }}}"
gives
msg: |-
keyone abc # comment
rtv 4 data2 # comment
longtexthere 1 # comment
keythree data3 # comment
keyfour data1234 # comment