BacklogZero®

Ansible in a Minute · Ansible Core ·

Use search to match a pattern anywhere in a string

Short answer

Use the Jinja search test in when to match a regex pattern anywhere in a string.

Ansible in a Minute — search string test

Request

playbook with vars.url set to https://example.com/users/foo/resources/bar; one debug task with when: url is search("users/.*/resources"); no set_fact, no uri, no in operator

Example

A quick heads-up: Every environment is different. Review and test this example before you run it on systems you care about.

YAML
---
# Prompt: playbook with vars.url set to https://example.com/users/foo/resources/bar; one debug task with when: url is search("users/.*/resources"); no set_fact, no uri, no in operator
- name: Playbook with vars.url set to https://example.com/users/foo/resources/bar
  hosts: all
  gather_facts: false
  vars:
    url: "https://example.com/users/foo/resources/bar"
  tasks:
    - name: Debug URL if it matches the pattern
      ansible.builtin.debug:
        msg: "URL matches the pattern"
      when: url is search("users/.*/resources")

How it works

search returns true when the regex pattern appears anywhere in the string. Use search in when, failed_when, or until. match is different. match requires the pattern at the start of the string.

When to use it

  • Branching on URL or path fragments
  • Matching CLI or API output that contains a known pattern

Requirements

  • Ansible: >=2.14

Validation

  • Syntax validated
  • Not execution-tested
  • Last verified 2026-09-05

Notes

Use is search("pattern") for a match anywhere in the string. Use is match("pattern") when the pattern must start at the beginning. Prefer Jinja test syntax (is search) over filter syntax.

Reference

Try it with BacklogZero

Ask BacklogZero to generate this automation for your environment.

Get BacklogZero today

Related guides

Back to Ansible in a Minute

Use search to match a pattern anywhere in a string · Level Up Labs