ansibleansible-facts

Extract a substring from a variable in Ansible


I want to remove a specific substring from a variable in Ansible and store the result into another variable. Say I have something like below:

greeting: "Hello_World"

I want to remove the substring "_World" from greeting and store the result in another Ansible variable.

Example: greet_word: "Hello"

Thanks in advance!


Solution

  • Q: "Remove the substring '_World'"

    A: There are more options:

    greet_word: "{{ greeting | regex_replace('^(.*)_World(.*)$', '\\1\\2') }}"
    

    gives

    greet_word: Hello
    
    greet_word: "{{ greeting.split('_').0 }}
    
    greet_word: "{{ greeting.split('_') | first }}
    
    greet_word: "{{ greeting | replace('_World', '') }}"