Ansible 截断连接字符串 [英] Ansible truncate concatentated string
问题描述
我正在 Ansible 中生成一个 yaml 模板,我试图截断两个连接的字符串:这里下面的代码不起作用,因为连接没有正确地传递到 regex_replace 中.我只想要前 n 个字符(本例中的前 10 个字符)
I am generating an yaml template in Ansible and I am trying to truncate two concatenated strings: Here the following code doesn't work because of the concatenation does not pipe into the regex_replace correctly. I am only wanting the first n characters (first 10 characters in this example)
通常我可以将这两个组合成一个变量然后再做
Normally I could just combine these two into one variable and then do
{{variabel [:10] }}
但在这种情况下我无法做到这一点,因为我正在处理的文件正在与变量组合,然后另存为 yaml 文件...
But I am no able to do that in this case because the file I am working in is getting combined with variables and then saved as a yaml file...
基本上我想在不先组合或创建新变量的情况下截断字符串.
Basically I want to truncate the string without first combining or creating a new variable.
- hosts: localhost
gather_facts: False
vars:
foo: "somelongstring"
tasks:
- name: Display debug output
debug:
msg: "{{ foo + '-moretext' | regex_replace('^.{0,10}', '\\1') }} "
推荐答案
要将过滤器或运算符应用于复杂表达式(过滤器序列除外),您必须用括号将其括起来.
To apply a filter or an operator on a complex expression (other than a sequence of filters), you have to surround it with parenthesis.
因此要在 1 个操作中截断连接的结果:
So to truncate the result of a concatenation in 1 action:
msg: "{{ (foo + '-moretext')[:10] }} "
顺便说一句,还有 truncate
过滤器一个>:
BTW, there is also the truncate
filter:
msg: "{{ (foo + '-moretext') | truncate(10, True, '') }} "
这篇关于Ansible 截断连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!