| 1 |
# (c) 2013, Jan-Piet Mens <jpmens(at)gmail.com> |
| 2 |
# (c) 2017 Ansible Project |
| 3 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
DOCUMENTATION = r""" |
| 7 |
name: csvfile |
| 8 |
author: Jan-Piet Mens (@jpmens) <jpmens(at)gmail.com> |
| 9 |
version_added: "1.5" |
| 10 |
short_description: read data from a TSV or CSV file |
| 11 |
description: |
| 12 |
- The csvfile lookup reads the contents of a file in CSV (comma-separated value) format. |
| 13 |
The lookup looks for the row where the first column matches keyname (which can be multiple words) |
| 14 |
and returns the value in the O(col) column (default 1, which indexed from 0 means the second column in the file). |
| 15 |
- At least one keyname is required, provided as a positional argument(s) to the lookup. |
| 16 |
options: |
| 17 |
col: |
| 18 |
description: column to return (0 indexed). |
| 19 |
default: 1 |
| 20 |
type: int |
| 21 |
keycol: |
| 22 |
description: column to search in (0 indexed). |
| 23 |
default: 0 |
| 24 |
type: int |
| 25 |
version_added: "2.17" |
| 26 |
default: |
| 27 |
description: what to return if the value is not found in the file. |
| 28 |
delimiter: |
| 29 |
description: field separator in the file, for a tab you can specify V(TAB) or V(\\t). |
| 30 |
default: TAB |
| 31 |
file: |
| 32 |
description: name of the CSV/TSV file to open. |
| 33 |
default: ansible.csv |
| 34 |
encoding: |
| 35 |
description: Encoding (character set) of the used CSV file. |
| 36 |
default: utf-8 |
| 37 |
version_added: "2.1" |
| 38 |
notes: |
| 39 |
- The default is for TSV files (tab delimited) not CSV (comma delimited) ... yes the name is misleading. |
| 40 |
- As of version 2.11, the search parameter (text that must match the first column of the file) and filename parameter can be multi-word. |
| 41 |
- For historical reasons, in the search keyname, quotes are treated |
| 42 |
literally and cannot be used around the string unless they appear |
| 43 |
(escaped as required) in the first column of the file you are parsing. |
| 44 |
seealso: |
| 45 |
- ref: playbook_task_paths |
| 46 |
description: Search paths used for relative files. |
| 47 |
""" |
| 48 |
|
| 49 |
EXAMPLES = """ |
| 50 |
- name: Match 'Li' on the first column, return the second column (0 based index) |
| 51 |
ansible.builtin.debug: msg="The atomic number of Lithium is {{ lookup('ansible.builtin.csvfile', 'Li file=elements.csv delimiter=,') }}" |
| 52 |
|
| 53 |
- name: msg="Match 'Li' on the first column, but return the 3rd column (columns start counting after the match)" |
| 54 |
ansible.builtin.debug: msg="The atomic mass of Lithium is {{ lookup('ansible.builtin.csvfile', 'Li file=elements.csv delimiter=, col=2') }}" |
| 55 |
|
| 56 |
# Contents of bgp_neighbors.csv |
| 57 |
# 127.0.0.1,10.0.0.1,24,nones,lola,pepe,127.0.0.2 |
| 58 |
# 128.0.0.1,10.1.0.1,20,notes,lolita,pepito,128.0.0.2 |
| 59 |
# 129.0.0.1,10.2.0.1,23,nines,aayush,pepete,129.0.0.2 |
| 60 |
|
| 61 |
- name: Define values from CSV file, this reads file in one go, but you could also use col= to read each in it's own lookup. |
| 62 |
ansible.builtin.set_fact: |
| 63 |
'{{ columns[item|int] }}': "{{ csvline }}" |
| 64 |
vars: |
| 65 |
csvline: "{{ lookup('csvfile', bgp_neighbor_ip, file='bgp_neighbors.csv', delimiter=',', col=item) }}" |
| 66 |
columns: ['loop_ip', 'int_ip', 'int_mask', 'int_name', 'local_as', 'neighbour_as', 'neight_int_ip'] |
| 67 |
bgp_neighbor_ip: '127.0.0.1' |
| 68 |
loop: '{{ range(columns|length|int) }}' |
| 69 |
delegate_to: localhost |
| 70 |
delegate_facts: true |
| 71 |
|
| 72 |
# Contents of people.csv |
| 73 |
# # Last,First,Email,Extension |
| 74 |
# Smith,Jane,[email protected],1234 |
| 75 |
|
| 76 |
- name: Specify the column (by keycol) in which the string should be searched |
| 77 |
assert: |
| 78 |
that: |
| 79 |
- lookup('ansible.builtin.csvfile', 'Jane', file='people.csv', delimiter=',', col=0, keycol=1) == "Smith" |
| 80 |
|
| 81 |
# Contents of debug.csv |
| 82 |
# test1 ret1.1 ret2.1 |
| 83 |
# test2 ret1.2 ret2.2 |
| 84 |
# test3 ret1.3 ret2.3 |
| 85 |
|
| 86 |
- name: "Lookup multiple keynames in the first column (index 0), returning the values from the second column (index 1)" |
| 87 |
debug: |
| 88 |
msg: "{{ lookup('csvfile', 'test1', 'test2', file='debug.csv', delimiter=' ') }}" |
| 89 |
|
| 90 |
- name: Lookup multiple keynames using old style syntax |
| 91 |
debug: |
| 92 |
msg: "{{ lookup('csvfile', term1, term2) }}" |
| 93 |
vars: |
| 94 |
term1: "test1 file=debug.csv delimiter=' '" |
| 95 |
term2: "test2 file=debug.csv delimiter=' '" |
| 96 |
""" |
| 97 |
|
| 98 |
RETURN = """ |
| 99 |
_raw: |
| 100 |
description: |
| 101 |
- value(s) stored in file column |
| 102 |
type: list |
| 103 |
elements: str |
| 104 |
""" |
| 105 |
|
| 106 |
import csv |
| 107 |
|
| 108 |
from collections.abc import MutableSequence |
| 109 |
|
| 110 |
from ansible.errors import AnsibleError |
| 111 |
from ansible.parsing.splitter import parse_kv |
| 112 |
from ansible.plugins.lookup import LookupBase |
| 113 |
|
| 114 |
|
| 115 |
class LookupModule(LookupBase): |
| 116 |
|
| 117 |
def read_csv(self, filename, key, delimiter, encoding='utf-8', dflt=None, col=1, keycol=0): |
| 118 |
with open(filename, encoding=encoding) as f: |
| 119 |
for row in csv.reader(f, dialect=csv.excel, delimiter=delimiter): |
| 120 |
if row and row[keycol] == key: |
| 121 |
return row[col] |
| 122 |
|
| 123 |
return dflt |
| 124 |
|
| 125 |
def run(self, terms, variables=None, **kwargs): |
| 126 |
ret = [] |
| 127 |
|
| 128 |
self.set_options(var_options=variables, direct=kwargs) |
| 129 |
|
| 130 |
# populate options |
| 131 |
paramvals = self.get_options() |
| 132 |
|
| 133 |
if not terms: |
| 134 |
raise AnsibleError('Search key is required but was not found') |
| 135 |
|
| 136 |
for term in terms: |
| 137 |
kv = parse_kv(term) |
| 138 |
|
| 139 |
if '_raw_params' not in kv: |
| 140 |
raise AnsibleError('Search key is required but was not found') |
| 141 |
|
| 142 |
key = kv['_raw_params'] |
| 143 |
|
| 144 |
# parameters override per term using k/v |
| 145 |
reset_params = False |
| 146 |
for name, value in kv.items(): |
| 147 |
if name == '_raw_params': |
| 148 |
continue |
| 149 |
if name not in paramvals: |
| 150 |
raise ValueError(f'{name!r} is not a valid option') |
| 151 |
|
| 152 |
self._deprecate_inline_kv() |
| 153 |
self.set_option(name, value) |
| 154 |
reset_params = True |
| 155 |
|
| 156 |
if reset_params: |
| 157 |
paramvals = self.get_options() |
| 158 |
|
| 159 |
# default is just placeholder for real tab |
| 160 |
if paramvals['delimiter'] == 'TAB': |
| 161 |
paramvals['delimiter'] = "\t" |
| 162 |
|
| 163 |
lookupfile = self.find_file_in_search_path(variables, 'files', paramvals['file']) |
| 164 |
var = self.read_csv(lookupfile, key, paramvals['delimiter'], paramvals['encoding'], paramvals['default'], paramvals['col'], paramvals['keycol']) |
| 165 |
if var is not None: |
| 166 |
if isinstance(var, MutableSequence): |
| 167 |
ret.extend(var) |
| 168 |
else: |
| 169 |
ret.append(var) |
| 170 |
|
| 171 |
return ret |