如何格式化Ansible值中的变量 [英] How to format a variable in Ansible value

查看:277
本文介绍了如何格式化Ansible值中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于Ansible通过Jinja2处理所有变量,并且可以执行以下操作:

Given that Ansible processes all variables through Jinja2, and doing something like this is possible:

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

正确将字符串插值为:

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"}

那为什么不起作用:

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

这显然会引起某种解析问题,从而导致我们所需的字符串变得冗长:

This apparently causes some sort of parsing issue which results in our desired string being rendered verbose:

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

请注意,在上面的示例中,item是字符串,因为with_sequence的默认格式为%d,并且format()不会将item的值强制转换为字符串插值所需的格式%02d,因此需要使用int()进行投射.

Noting that in the above example item is a string because the default format of with_sequence is %d, and format() doesn't cast the value of item to the format required by the string interpolation %02d, hence the need to cast with int().

这是错误还是我错过了什么?

Is this a bug or am I missing something?

推荐答案

我花了几次尝试才能解决这个问题,但是请尝试这样做:

It took me a couple of tries to get this right, but try this, instead:

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

Jinja2有点有趣.

Jinja2 is a bit funny.

这篇关于如何格式化Ansible值中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆