Filter a substring matching a pattern from an ansible variable and assign matched substring to another variable

Pranjal Mittal picture Pranjal Mittal · Jun 7, 2016 · Viewed 23.3k times · Source

Let's say we have a long ansible string variable mystr. We have a regex pattern say substr_pattern and a substring matching this pattern is to be filtered out from mystr and to be assigned to another variable substr. There seems to be no obvious way to do this in ansible from the docs on playbook_filters though it is simple to do this with re module in python itself.

There are 3 methods given in the ansible docs and none of them seems to solve my problem:

  1. match: This filter returns true/false depending on whether the entire pattern matches the entire string but does not return matched group/substring.

  2. search: Used to filter substr in a bigger string. But like match, only returns true/false and not matched group/substring that is needed here.

  3. regex_replace: This is used to replace a matched pattern in a string with another string. But it's not clear how to register the substring/group corresponding to the matched pattern into a new variable.

Is there anything that I am missing? Or is this a missing feature in ansible?

Ansible Version: 2.1

Example:

mystr: "This is the long string. With a url. http://example.org/12345"
pattern: "http:\/\/example.org\/(\d+)"
substr: 12345   # First matched group i.e. \\1

Summary: How to get the substring matching the pattern from mystr and register that to an ansible variable substr?

Answer

udondan picture udondan · Jun 7, 2016

If you can modify the pattern, you could use the regex_replace filter and replace the whole string with only the matched digits.

mystr | regex_replace('^.*http:\/\/example.org\/(\d+).*?$', '\\1')

To assign the result to a new variable, you can use the set_fact module.

- set_fact:
    substr: "{{ mystr | regex_replace('^.*http:\/\/example.org\/(\d+).*?$', '\\1') }}"