Travis
Travis

Reputation: 444

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

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:

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

Upvotes: 3

Views: 1827

Answers (1)

larsks
larsks

Reputation: 312868

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"
}

Upvotes: 2

Related Questions