Ansible截断合并字符串 [英] Ansible truncate concatentated string

查看:360
本文介绍了Ansible截断合并字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在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屋!

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