Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible regex_search stdout not working, but works in regex101.com

Tags:

regex

ansible

I've read a thousand of the Ansible regex_search questions on here and have not found a satisfying answer.

Here's the test playbook. backup_stdout is set identically to what I get from the backup utility:

---

- hosts: localhost
  connection: local
  gather_facts: no
  vars:
    backup_stdout: |-
      Saving active configuration...
      /var/local/ucs/f5-apm-1625-081021.ucs is saved.
  tasks:
    - name: Get the backup name
      ansible.builtin.set_fact:
        backup_name: "{{ backup_stdout | regex_search(stdout_regex, multiline=True) }}"
      vars:
        stdout_regex: '"\/var.*ucs\b"gm'
      failed_when: backup_name == ''

    - debug:
        var: backup_name

I can't get the regex_search to produce a match. Here's the same code on regex101, which shows that it does match. I've tried the following:

  • with/without the multiline
  • with/without the trailing '\\1' in the expression
  • with/without passing the result to the | first filter
  • using ^\/var.*ucs instead of the word boundary (also matches on regex101)

So far, no matter what I've tried, I can't get the Ansible to match. Any help appreciated.

like image 435
Travis Avatar asked Jan 01 '26 07:01

Travis


1 Answers

You've got some weird quoting in your regular expression that is causing problems. Because you've written:

stdout_regex: '"\/var.*ucs\b"gm'

You're passing the literal value "\/var.*ucs\b"gm to regex_search. There are no quotes (nor is there a gm) in the content of backup_stdout, so this is never going to match.

I think you want:

- hosts: localhost
  connection: local
  gather_facts: no
  vars:
    backup_stdout: |-
      Saving active configuration...
      /var/local/ucs/f5-apm-1625-081021.ucs is saved.
  tasks:
    - name: Get the backup name
      ansible.builtin.set_fact:
        backup_name: "{{ backup_stdout | regex_search(stdout_regex, multiline=True) }}"
      vars:
        stdout_regex: '/var.*ucs\b'
      failed_when: backup_name == ''

    - debug:
        var: backup_name

Which produces:

TASK [debug] *******************************************************************
ok: [localhost] => {
    "backup_name": "/var/local/ucs/f5-apm-1625-081021.ucs"
}
like image 176
larsks Avatar answered Jan 03 '26 02:01

larsks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!