Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible truncate concatentated string

Tags:

ansible

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')  }} "
like image 607
Brent Avatar asked Sep 08 '17 01:09

Brent


1 Answers

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, '') }} "
like image 131
zigarn Avatar answered Nov 17 '22 04:11

zigarn