How to format a variable in Ansible value

Given that Ansible processes all the variables through Jinja2 and does something like this:

- name: Debug sequence item value debug: msg={{ 'Item\:\ %s'|format(item) }} with_sequence: count=5 format="%02d" 

What correctly interpolates the string as:

 ok: [server.name] => (item=01) => {"item": "01", "msg": "Item: 01"} ok: [server.name] => (item=02) => {"item": "02", "msg": "Item: 02"} ok: [server.name] => (item=03) => {"item": "03", "msg": "Item: 03"} ok: [server.name] => (item=04) => {"item": "04", "msg": "Item: 04"} ok: [server.name] => (item=05) => {"item": "05", "msg": "Item: 05"} 

Why then this does not work:

 - name: Debug sequence item value debug: msg={{ 'Item\:\ %02d'|format(int(item)) }} with_sequence: count=5 

This, apparently, causes some kind of parsing problem, which leads to the fact that our desired string appears verbose:

 ok: [server.name] => (item=01) => {"item": "01", "msg": "{{Item\\:\\ %02d|format(int(item))}}"} 

Noting that in the above example, item is a string, since the default format with_sequence is %d , and format() does not pass the value of item to the format needed to interpolate the strings %02d , therefore it must be used with int() .

Is this a mistake or am I missing something?

+4
source share
1 answer

It took me a few attempts to do it right, but try this instead:

 debug: msg={{ 'Item\:\ %02d'|format(item|int) }} 

Jinja2 is a little funny.

+13
source

Source: https://habr.com/ru/post/1495259/


All Articles