43

When deploying with ansible, There's 1 specific case where I need to strip a string of a trailing -p substring.

The string somemachine-prod-p should become somemachine-prod only if the -p is at the end.

The substring function I saw I can use with Jinja does not fulfill my needs as I need to strip the end of the string, not the start.

Ideas?

Moshe
  • 4,635
  • 6
  • 32
  • 57

4 Answers4

98

Found it.

If anyone wants to know:

{% if name.endswith('-p') %}
{{ name[:-2] }}
{% else %}
{{ name }}
{% endif %}
Moshe
  • 4,635
  • 6
  • 32
  • 57
32

For simple substring ...

"{{var_name[start:end]}}"

where start is starting position (offset 0) and end is end position (offset 1) ... it seems!

The title of this question suggests just wanting to get a substring from a variable. And most other search results have similar titles but then give a specific response like splitting paths etc. This is for those of you that, like me, had trouble finding such a basic thing.

Straff
  • 5,499
  • 4
  • 33
  • 31
29

There is a nicer "oneliner": {{ name | regex_replace('-p$','') }}.

Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • This only works with a suitable filter registered, because `regex_replace` is not a default filter. This is the case in ansible, which provides [extra filters](https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html). If you want to you can also omit the last argument: `{{ name | regex_replace('-p$')`. – steve Oct 04 '19 at 08:11
  • 3
    Sorry for the above comment. I just realised, that this is actually and ansible specific question. I just came here by searching for jinja2. – steve Oct 04 '19 at 08:17
4

from the documentation You can wrap it up in condition

truncate(s, length=255, killwords=False, end='...', leeway=None)

Return a truncated copy of the string. The length is specified with the first parameter which defaults to 255. If the second parameter is true the filter will cut the text at length. Otherwise it will discard the last word. If the text was in fact truncated it will append an ellipsis sign ("..."). If you want a different ellipsis sign than "..." you can specify it using the third parameter. Strings that only exceed the length by the tolerance margin given in the fourth parameter will not be truncated.

{{ "foo bar baz qux"|truncate(9) }}

-> "foo..."

{{ "foo bar baz qux"|truncate(9, True) }}

-> "foo ba..."

{{ "foo bar baz qux"|truncate(11) }}

-> "foo bar baz qux"

{{ "foo bar baz qux"|truncate(11, False, '...', 0) }}

-> "foo bar..."

The default leeway on newer Jinja versions is 5 and was 0 before but can be reconfigured globally.