csvfile - add a keycol parameter to specify in which column to search. (#82242)

pull/82261/head
Herman van Rink 6 months ago committed by GitHub
parent 0a6779f6b7
commit d6a8df3218
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,4 @@
---
minor_changes:
- csvfile - add a keycol parameter to specify in which column to search.

@ -16,6 +16,11 @@ DOCUMENTATION = r"""
col:
description: column to return (0 indexed).
default: "1"
keycol:
description: column to search in (0 indexed).
default: 0
type: int
version_added: "2.17"
default:
description: what to return if the value is not found in the file.
delimiter:
@ -122,14 +127,14 @@ class CSVReader:
class LookupModule(LookupBase):
def read_csv(self, filename, key, delimiter, encoding='utf-8', dflt=None, col=1):
def read_csv(self, filename, key, delimiter, encoding='utf-8', dflt=None, col=1, keycol=0):
try:
f = open(to_bytes(filename), 'rb')
creader = CSVReader(f, delimiter=to_native(delimiter), encoding=encoding)
for row in creader:
if len(row) and row[0] == key:
if len(row) and row[keycol] == key:
return row[int(col)]
except Exception as e:
raise AnsibleError("csvfile: %s" % to_native(e))
@ -172,7 +177,7 @@ class LookupModule(LookupBase):
paramvals['delimiter'] = "\t"
lookupfile = self.find_file_in_search_path(variables, 'files', paramvals['file'])
var = self.read_csv(lookupfile, key, paramvals['delimiter'], paramvals['encoding'], paramvals['default'], paramvals['col'])
var = self.read_csv(lookupfile, key, paramvals['delimiter'], paramvals['encoding'], paramvals['default'], paramvals['col'], paramvals['keycol'])
if var is not None:
if isinstance(var, MutableSequence):
for v in var:

@ -41,6 +41,7 @@
assert:
that:
- lookup('csvfile', 'Smith', file='people.csv', delimiter=',', col=1) == "Jane"
- lookup('csvfile', 'Jane', file='people.csv', delimiter=',', col=0, keycol=1) == "Smith"
- lookup('csvfile', 'German von Lastname file=people.csv delimiter=, col=1') == "Demo"
- name: Check tab-separated file

Loading…
Cancel
Save