forked from joelwking/ansible-nxapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv_to_facts.py
107 lines (77 loc) · 2.49 KB
/
csv_to_facts.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/usr/bin/env python
"""
Copyright (c) 2015 World Wide Technology, Inc.
All rights reserved.
Revision history:
26 Sept 2015 | 1.0 - initial release
"""
DOCUMENTATION = '''
---
module: csv_to_facts.py
author: Joel W. King, World Wide Technology
version_added: "1.0"
short_description: Read a CSV file and output Ansible facts
description:
- Read the CSV file specified and output Ansible facts in the form of a list with each
element in the list as a dictionary using the column header as the key and the contents
of the cell as the value.
requirements:
- None
options:
src:
description:
- The CSV formatted input file
required: true
'''
EXAMPLES = '''
Running the module
ansible localhost -m csv_to_facts -a "src=/tmp/TonyA.csv"
In a role configuration, given a group and host entry
[asante]
NEX-3048-E.sandbox.wwtatc.local ansible_connection=local ansible_ssh_user=kingjoe hostname=13leafzn02-rp01
#
$ cat asante.yml
---
- name: Test Role
hosts: asante
roles:
- {role: excel_nxos, debug: on}
$ ansible-playbook asante.yml --ask-vault
'''
import csv
# ---------------------------------------------------------------------------
# read_csv_dict
# ---------------------------------------------------------------------------
def read_csv_dict(input_file):
"Read the CSV file and return as Ansible factsn"
result = {"ansible_facts":{}}
spreadsheet = {"spreadsheet":[]}
try:
with open(input_file) as csvfile:
reader = csv.DictReader(csvfile, delimiter=',', quotechar='"')
for row in reader:
spreadsheet["spreadsheet"].append(row)
except IOError:
return (1, "IOError on input file:%s" % input_file)
csvfile.close()
result["ansible_facts"] = spreadsheet
return (0, result)
# ---------------------------------------------------------------------------
# MAIN
# ---------------------------------------------------------------------------
def main():
" "
module = AnsibleModule(argument_spec = dict(
src = dict(required=True)
),
check_invalid_arguments=False,
add_file_common_args=True)
code, response = read_csv_dict(module.params["src"])
if code == 1:
module.fail_json(msg=response)
else:
module.exit_json(**response)
return code
from ansible.module_utils.basic import *
main()
#