Ansible truncate concatentated string

心已入冬 提交于 2021-01-27 13:09:23

问题


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

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

回答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.

So to truncate the result of a concatenation in 1 action:

msg: "{{ (foo  + '-moretext')[:10] }} "

BTW, there is also the truncate filter:

msg: "{{ (foo  + '-moretext') | truncate(10, True, '') }} "


来源:https://stackoverflow.com/questions/46107359/ansible-truncate-concatentated-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!