regex_replace by a var content in jinja template

2.2k Views Asked by At

I have a jinja template and i want to replace a string by the content of a variable

exemple :

ansible_hostname: 'host-to'
item.suffixe: 'cool'

the result will be : host-cool-to

I did this :

{{ ansible_hostname | regex_replace('-to', '-{{ item.suffixe }}-to') }}

of course the '-{{ item.suffixe }}-to' was not interpreted and the result is : host-{{ item.suffixe }}-to

Is it possible to use a variable in regex_replace ? How ? in the ansible exemple they don't show anythings like this

1

There are 1 best solutions below

0
On BEST ANSWER

Q: "Is it possible to use a variable in regex_replace ?"

A: Yes. It's possible. It's easier to put the parameters into variables. For example

    - debug:
        msg: "{{ hostname | regex_replace(regex, replace) }}"
      vars:
        hostname: host-to
        suffix: cool
        regex: '-to'
        replace: '-{{ suffix }}-to'

gives

  msg: host-cool-to