| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2018, Dag Wieers (@dagwieers) <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: read_csv |
| 11 |
short_description: Read a CSV file |
| 12 |
description: |
| 13 |
- Read a CSV file and return a list or a dictionary, containing one dictionary per row. |
| 14 |
author: |
| 15 |
- Dag Wieers (@dagwieers) |
| 16 |
extends_documentation_fragment: |
| 17 |
- community.general._attributes |
| 18 |
attributes: |
| 19 |
check_mode: |
| 20 |
support: full |
| 21 |
diff_mode: |
| 22 |
support: none |
| 23 |
options: |
| 24 |
path: |
| 25 |
description: |
| 26 |
- The CSV filename to read data from. |
| 27 |
type: path |
| 28 |
required: true |
| 29 |
aliases: [filename] |
| 30 |
key: |
| 31 |
description: |
| 32 |
- The column name used as a key for the resulting dictionary. |
| 33 |
- If O(key) is unset, the module returns a list of dictionaries, where each dictionary is a row in the CSV file. |
| 34 |
type: str |
| 35 |
dialect: |
| 36 |
description: |
| 37 |
- The CSV dialect to use when parsing the CSV file. |
| 38 |
- Possible values include V(excel), V(excel-tab) or V(unix). |
| 39 |
type: str |
| 40 |
default: excel |
| 41 |
fieldnames: |
| 42 |
description: |
| 43 |
- A list of field names for every column. |
| 44 |
- This is needed if the CSV does not have a header. |
| 45 |
type: list |
| 46 |
elements: str |
| 47 |
unique: |
| 48 |
description: |
| 49 |
- Whether the O(key) used is expected to be unique. |
| 50 |
type: bool |
| 51 |
default: true |
| 52 |
delimiter: |
| 53 |
description: |
| 54 |
- A one-character string used to separate fields. |
| 55 |
- When using this parameter, you change the default value used by O(dialect). |
| 56 |
- The default value depends on the dialect used. |
| 57 |
type: str |
| 58 |
skipinitialspace: |
| 59 |
description: |
| 60 |
- Whether to ignore any whitespaces immediately following the delimiter. |
| 61 |
- When using this parameter, you change the default value used by O(dialect). |
| 62 |
- The default value depends on the dialect used. |
| 63 |
type: bool |
| 64 |
strict: |
| 65 |
description: |
| 66 |
- Whether to raise an exception on bad CSV input. |
| 67 |
- When using this parameter, you change the default value used by O(dialect). |
| 68 |
- The default value depends on the dialect used. |
| 69 |
type: bool |
| 70 |
seealso: |
| 71 |
- plugin: ansible.builtin.csvfile |
| 72 |
plugin_type: lookup |
| 73 |
description: Can be used to do selective lookups in CSV files from Jinja. |
| 74 |
""" |
| 75 |
|
| 76 |
EXAMPLES = r""" |
| 77 |
# Example CSV file with header |
| 78 |
# |
| 79 |
# name,uid,gid |
| 80 |
# dag,500,500 |
| 81 |
# jeroen,501,500 |
| 82 |
|
| 83 |
# Read a CSV file and access user 'dag' |
| 84 |
- name: Read users from CSV file and return a dictionary |
| 85 |
community.general.read_csv: |
| 86 |
path: users.csv |
| 87 |
key: name |
| 88 |
register: users |
| 89 |
delegate_to: localhost |
| 90 |
|
| 91 |
- ansible.builtin.debug: |
| 92 |
msg: 'User {{ users.dict.dag.name }} has UID {{ users.dict.dag.uid }} and GID {{ users.dict.dag.gid }}' |
| 93 |
|
| 94 |
# Read a CSV file and access the first item |
| 95 |
- name: Read users from CSV file and return a list |
| 96 |
community.general.read_csv: |
| 97 |
path: users.csv |
| 98 |
register: users |
| 99 |
delegate_to: localhost |
| 100 |
|
| 101 |
- ansible.builtin.debug: |
| 102 |
msg: 'User {{ users.list.1.name }} has UID {{ users.list.1.uid }} and GID {{ users.list.1.gid }}' |
| 103 |
|
| 104 |
# Example CSV file without header and semi-colon delimiter |
| 105 |
# |
| 106 |
# dag;500;500 |
| 107 |
# jeroen;501;500 |
| 108 |
|
| 109 |
# Read a CSV file without headers |
| 110 |
- name: Read users from CSV file and return a list |
| 111 |
community.general.read_csv: |
| 112 |
path: users.csv |
| 113 |
fieldnames: name,uid,gid |
| 114 |
delimiter: ';' |
| 115 |
register: users |
| 116 |
delegate_to: localhost |
| 117 |
""" |
| 118 |
|
| 119 |
RETURN = r""" |
| 120 |
dict: |
| 121 |
description: The CSV content as a dictionary. |
| 122 |
returned: success |
| 123 |
type: dict |
| 124 |
sample: |
| 125 |
dag: |
| 126 |
name: dag |
| 127 |
uid: 500 |
| 128 |
gid: 500 |
| 129 |
jeroen: |
| 130 |
name: jeroen |
| 131 |
uid: 501 |
| 132 |
gid: 500 |
| 133 |
list: |
| 134 |
description: The CSV content as a list. |
| 135 |
returned: success |
| 136 |
type: list |
| 137 |
sample: |
| 138 |
- name: dag |
| 139 |
uid: 500 |
| 140 |
gid: 500 |
| 141 |
- name: jeroen |
| 142 |
uid: 501 |
| 143 |
gid: 500 |
| 144 |
""" |
| 145 |
|
| 146 |
from ansible.module_utils.basic import AnsibleModule |
| 147 |
|
| 148 |
from ansible_collections.community.general.plugins.module_utils._csv import ( |
| 149 |
CSVError, |
| 150 |
CustomDialectFailureError, |
| 151 |
DialectNotAvailableError, |
| 152 |
initialize_dialect, |
| 153 |
read_csv, |
| 154 |
) |
| 155 |
|
| 156 |
|
| 157 |
def main(): |
| 158 |
module = AnsibleModule( |
| 159 |
argument_spec=dict( |
| 160 |
path=dict(type="path", required=True, aliases=["filename"]), |
| 161 |
dialect=dict(type="str", default="excel"), |
| 162 |
key=dict(type="str", no_log=False), |
| 163 |
fieldnames=dict(type="list", elements="str"), |
| 164 |
unique=dict(type="bool", default=True), |
| 165 |
delimiter=dict(type="str"), |
| 166 |
skipinitialspace=dict(type="bool"), |
| 167 |
strict=dict(type="bool"), |
| 168 |
), |
| 169 |
supports_check_mode=True, |
| 170 |
) |
| 171 |
|
| 172 |
path = module.params["path"] |
| 173 |
dialect = module.params["dialect"] |
| 174 |
key = module.params["key"] |
| 175 |
fieldnames = module.params["fieldnames"] |
| 176 |
unique = module.params["unique"] |
| 177 |
|
| 178 |
dialect_params = { |
| 179 |
"delimiter": module.params["delimiter"], |
| 180 |
"skipinitialspace": module.params["skipinitialspace"], |
| 181 |
"strict": module.params["strict"], |
| 182 |
} |
| 183 |
|
| 184 |
try: |
| 185 |
dialect = initialize_dialect(dialect, **dialect_params) |
| 186 |
except (CustomDialectFailureError, DialectNotAvailableError) as e: |
| 187 |
module.fail_json(msg=f"{e}") |
| 188 |
|
| 189 |
try: |
| 190 |
with open(path, "rb") as f: |
| 191 |
data = f.read() |
| 192 |
except OSError as e: |
| 193 |
module.fail_json(msg=f"Unable to open file: {e}") |
| 194 |
|
| 195 |
reader = read_csv(data, dialect, fieldnames) |
| 196 |
|
| 197 |
if key and key not in reader.fieldnames: |
| 198 |
module.fail_json(msg=f"Key '{key}' was not found in the CSV header fields: {', '.join(reader.fieldnames)}") |
| 199 |
|
| 200 |
data_dict = dict() |
| 201 |
data_list = list() |
| 202 |
|
| 203 |
if key is None: |
| 204 |
try: |
| 205 |
for row in reader: |
| 206 |
data_list.append(row) |
| 207 |
except CSVError as e: |
| 208 |
module.fail_json(msg=f"Unable to process file: {e}") |
| 209 |
else: |
| 210 |
try: |
| 211 |
for row in reader: |
| 212 |
if unique and row[key] in data_dict: |
| 213 |
module.fail_json(msg=f"Key '{key}' is not unique for value '{row[key]}'") |
| 214 |
data_dict[row[key]] = row |
| 215 |
except CSVError as e: |
| 216 |
module.fail_json(msg=f"Unable to process file: {e}") |
| 217 |
|
| 218 |
module.exit_json(dict=data_dict, list=data_list) |
| 219 |
|
| 220 |
|
| 221 |
if __name__ == "__main__": |
| 222 |
main() |