Search code examples
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
    
    • Split the string on the underscore '_' and take the first item. The expressions below give the same result.
    greet_word: "{{ greeting.split('_').0 }}
    
    greet_word: "{{ greeting.split('_') | first }}
    
    • Use the Jinja filter replace. The expression below gives the same result.
    greet_word: "{{ greeting | replace('_World', '') }}"