ansible/ansible — pull request #4846 by jpmens (2013-11-08 08:29:30+00:00)
Title: new lookup-plugin: lsearch (linear search in text file)

This plugin will search a given text file for a key and return the string found or a configurable default. The general syntax of the plugin is

```
lookup('lsearch', "key file=/path/to/file.txt")
lookup('lsearch', "key2 file=/path/to/other.txt default=ENOENT")
```

Example:

### Playbook

```yaml

- hosts: 127.0.0.1
connection: local
gather_facts: False
tasks:
- action: debug msg="{{ lookup('lsearch', 'dos file=input.txt') }}"
- action: debug msg="{{ lookup('lsearch', 'tres file=other.txt') }}"
- action: debug msg="{{ lookup('lsearch', 'enoent file=input.txt') }}"
- action: template src=lsearch-template.in dest=/tmp/out.file.{{ item }}
with_items:
- a
- b
- c
- d
```

### input.txt

```

uno: One
dos Two
tres Three means 3
dos Two #2
tres TRESSS
#blu kdkdkd
a AAAAAAAAAAAAAAAAAAAA
b BBBBBBBBBBBBBBBBBBBB
d DDDDDDDDDDDDDDDDDDDD
quatro Vier
```

### Template

```jinja2

quatro is: {{ lookup('lsearch', 'quatro file=input.txt') }}
doing item: {{item}}

{# Build param consisting of key and file= #}
{% set param = ' '.join(( item, "file=input.txt", "default=OhNo!")) %}

param is: {{ param }}
result is: {{ lookup('lsearch', param) }}

{% set val = lookup('lsearch', param) %}
value is: {{ val }}
```

### run

```

PLAY [127.0.0.1] **************************************************************

TASK: [debug msg="Two"] *******************************************************
ok: [127.0.0.1] => {
"msg": "Two"
}

TASK: [debug msg=""] **********************************************************
ok: [127.0.0.1] => {
"msg": ""
}

TASK: [debug msg=""] **********************************************************
ok: [127.0.0.1] => {
"msg": ""
}

TASK: [template src=lsearch-template.in dest=/tmp/out.file.{{item}}] **********
changed: [127.0.0.1] => (item=a)
changed: [127.0.0.1] => (item=b)
changed: [127.0.0.1] => (item=c)
changed: [127.0.0.1] => (item=d)

PLAY RECAP ********************************************************************
127.0.0.1 : ok=4 changed=1 unreachable=0 failed=0
```

### out.file.a

```

quatro is: Vier
doing item: a

param is: a file=input.txt default=OhNo!
result is: AAAAAAAAAAAAAAAAAAAA

value is: AAAAAAAAAAAAAAAAAAAA
```