diff --git a/changelogs/fragments/csvfile-keycol.yml b/changelogs/fragments/csvfile-keycol.yml new file mode 100644 index 00000000000..66819ba2f73 --- /dev/null +++ b/changelogs/fragments/csvfile-keycol.yml @@ -0,0 +1,4 @@ +--- + +minor_changes: + - csvfile - add a keycol parameter to specify in which column to search. diff --git a/lib/ansible/plugins/lookup/csvfile.py b/lib/ansible/plugins/lookup/csvfile.py index a82a7e76131..778138847ae 100644 --- a/lib/ansible/plugins/lookup/csvfile.py +++ b/lib/ansible/plugins/lookup/csvfile.py @@ -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: diff --git a/test/integration/targets/lookup_csvfile/tasks/main.yml b/test/integration/targets/lookup_csvfile/tasks/main.yml index 758da71e876..370dc0510b8 100644 --- a/test/integration/targets/lookup_csvfile/tasks/main.yml +++ b/test/integration/targets/lookup_csvfile/tasks/main.yml @@ -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