Sugetha Chandran
Sugetha Chandran

Reputation: 89

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!

Upvotes: 5

Views: 28566

Answers (2)

Vladimir Botka
Vladimir Botka

Reputation: 68294

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', '') }}"

Upvotes: 19

Temirlan Bolurov
Temirlan Bolurov

Reputation: 11

You can try set_fact module and regular expressions

    - name: Extract substring from a variable
      set_fact:
        new_variable: "{{ variable | regex_search() }}"

Can test regular expressions with any online service, also can check what you are getting with debug

Upvotes: 0

Related Questions