Interview Prep/Ansible/Jinja2, Conditionals and Loops

How do `regex_replace` and `regex_search` work?

IntermediateConceptJinja2, Conditionals and Loops
Answer
"{{ 'web-prod-01' | regex_replace('-[0-9]+$', '') }}"          # web-prod
"{{ 'v1.4.2' | regex_replace('^v', '') }}"                      # 1.4.2
"{{ out.stdout | regex_search('version (\\d+\\.\\d+)', '\\1') }}"  # ['1.4']
"{{ lines | map('regex_search', '^ERROR.*') | select | list }}"

regex_search returns the match, or an empty string (or None when no match depending on version) if nothing matches, so guard with | default. With a capture group argument it returns a list. In YAML double-quoted strings, escape backslashes (\\d), or use single quotes.

All Ansible questions Roadmap: Ansible

More on Jinja2, Conditionals and Loops