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

查看:30
本文介绍了如何在 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天全站免登陆