ansible/ansible — pull request #4987 by jpmens (2013-11-21 08:45:28+00:00)
Title: New lookup plugin csvreader

The `csvfile` lookup plugin results from a discussion on ansible-devel and supersedes #4846. This plugin reads CSV and TSV (default) data. (I chose to use TAB as default delimiter because that's a bit difficult to specify in a playbook. Even so, this delimiter can explicitly be specified as "TAB".)

`csvfile` is used as follows:

```
lookup('csvfile', 'key')
lookup('csvfile', 'key file=abc.csv')
lookup('csvfile', 'key delimiter=; file=abc.csv')
lookup('csvfile', 'key col=2') # returns content of column 2 only (default: column 1; 0 is key)
```

* `key` is the key we want to look up in column 0 of the CSV file
* `file` is the CSV file to read (default: `ansible.csv`)
* `col` is the column number to be returned (0 is the key) and defaults to 1
* `delimiter` is a single character which specifies how fields in `file` are separated. Default is TAB. (As a special case, `delimiter=TAB` can be used to mean `delimiter=\t`)
* `default` is the string to return if `key` isn't found and defaults to an empty string.

### input.csv (here with ; as delimiter)

```txt
# bla bla bla
uno;This is number one; col-1
dos;This is number two;col-2
bomb;tcp://192.168.1.2:328/
tres;El tercero!;col-3
jane;Jane Smith
alice;Alicia Ejemplo
joe;Joe's Acme Corp; and whatnot
```

### Playbook

```yaml
- hosts:
- 127.0.0.1
gather_facts: False
connection: local
vars:
- conntype: "{{ lookup('csvfile', 'bomb file=input.csv delimiter=; col=1') }}"
- names: [ jane, notthere, alice ]
tasks:
- action: debug msg="conntype={{ conntype }}"
- action: debug msg="host={{ lookup('csvfile', 'host file=input.txt col=1 delimiter=TAB') }}"
- action: template src=csv-template.in dest=/tmp/out.file
```

### Template

```jinja2

{% for name in names -%}

{# Build param consisting of key and file= #}
{%
set param = ' '.join(( name, "file=input.csv", "default=OhNo!", "delimiter=;"))
-%}
{% set val = lookup('csvfile', param) -%}
{{ name }} is in fact "{{ val }}"
{% endfor %}
```

### run

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

TASK: [debug msg="conntype=tcp://192.168.1.2:328/"] ***************************
ok: [127.0.0.1] => {
"msg": "conntype=tcp://192.168.1.2:328/"
}

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

TASK: [template src=csv-template.in dest=/tmp/out.file] ***********************
changed: [127.0.0.1]

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

### /tmp/out.file

```

jane is in fact "Jane Smith"
notthere is in fact "OhNo!"
alice is in fact "Alicia Ejemplo"
```