ansibleansible-template

regex_replace by a var content in jinja template


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


Solution

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

    A: Yes. It's possible. It's easier to put the parameters into the 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