community.general/lib/ansible/plugins/lookup/csvfile.py

111 lines
3.4 KiB
Python
Raw Normal View History

2015-01-09 15:37:31 +00:00
# (c) 2013, Jan-Piet Mens <jpmens(at)gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
2015-04-13 20:28:01 +00:00
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
2015-01-09 15:37:31 +00:00
import codecs
import csv
from ansible.errors import AnsibleError
2015-01-09 15:37:31 +00:00
from ansible.plugins.lookup import LookupBase
from ansible.module_utils._text import to_bytes, to_native, to_text
2015-01-09 15:37:31 +00:00
class CSVRecoder:
"""
Iterator that reads an encoded stream and reencodes the input to UTF-8
"""
def __init__(self, f, encoding='utf-8'):
self.reader = codecs.getreader(encoding)(f)
def __iter__(self):
return self
def next(self):
return self.reader.next().encode("utf-8")
class CSVReader:
"""
A CSV reader which will iterate over lines in the CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding='utf-8', **kwds):
f = CSVRecoder(f, encoding)
self.reader = csv.reader(f, dialect=dialect, **kwds)
def next(self):
row = self.reader.next()
return [to_text(s) for s in row]
def __iter__(self):
return self
2015-01-09 15:37:31 +00:00
class LookupModule(LookupBase):
def read_csv(self, filename, key, delimiter, encoding='utf-8', dflt=None, col=1):
2015-01-09 15:37:31 +00:00
try:
f = open(filename, 'r')
creader = CSVReader(f, delimiter=to_bytes(delimiter), encoding=encoding)
2015-01-09 15:37:31 +00:00
for row in creader:
if row[0] == key:
return row[int(col)]
2015-04-13 16:35:20 +00:00
except Exception as e:
raise AnsibleError("csvfile: %s" % to_native(e))
2015-01-09 15:37:31 +00:00
return dflt
def run(self, terms, variables=None, **kwargs):
ret = []
2015-01-09 15:37:31 +00:00
for term in terms:
params = term.split()
key = params[0]
paramvals = {
'col' : "1", # column to return
2015-01-09 15:37:31 +00:00
'default' : None,
'delimiter' : "TAB",
'file' : 'ansible.csv',
'encoding' : 'utf-8',
2015-01-09 15:37:31 +00:00
}
# parameters specified?
try:
for param in params[1:]:
name, value = param.split('=')
assert(name in paramvals)
paramvals[name] = value
2015-04-13 16:35:20 +00:00
except (ValueError, AssertionError) as e:
2015-01-09 15:37:31 +00:00
raise AnsibleError(e)
if paramvals['delimiter'] == 'TAB':
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'])
2015-01-09 15:37:31 +00:00
if var is not None:
if type(var) is list:
for v in var:
ret.append(v)
else:
ret.append(var)
return ret