-
Notifications
You must be signed in to change notification settings - Fork 0
/
inventory.py
executable file
·95 lines (68 loc) · 2.66 KB
/
inventory.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
#!/usr/bin/env python3
'''
Example custom dynamic inventory script for Ansible, in Python.
'''
import os
import sys
import argparse
import csv
try:
import json
except ImportError:
import simplejson as json
csvfilepath = "input.csv"
jsonFilePath = "output.json"
class ExampleInventory(object):
def __init__(self):
self.inventory = {}
self.read_cli_args()
# Called with `--list`.
if self.args.list:
self.inventory = self.example_inventory()
# Called with `--host [hostname]`.
elif self.args.host:
# Not implemented, since we return _meta info `--list`.
self.inventory = self.empty_inventory()
# If no groups or vars are present, return an empty inventory.
else:
self.inventory = self.empty_inventory()
print( json.dumps(self.inventory))
# Example inventory for testing.
def example_inventory(self):
# Converting input.csv to dictionary
rows = {}
new_data_dict = {}
with open(csvfilepath, 'r') as data_file:
data = csv.DictReader(data_file, delimiter=",")
for row in data:
item = dict()
temp_list = []
temp_list = row["hosts"].split(",")
item["hosts"] = temp_list
item["vars"] = dict()
item["vars"]["ansible_ssh_user"] = row["ansible_ssh_user"]
item["vars"]["ansible_ssh_private_key_file"] = row["ansible_ssh_private_key_file"]
new_data_dict[row["Groups"]] = item
item = {}
item['hostvars'] = {}
new_data_dict[row["_meta"]] = item
# converting new_data_dict dictionary to Json
with open(jsonFilePath, "w") as jsonFile:
jsonFile.write(json.dumps(new_data_dict, indent=4))
#print (json.dumps(new_data_dict))
#data = json.load(read_file)
#return (json.load(new_data_dict))
with open(jsonFilePath, "r") as read_file:
data = json.load(read_file)
return data
# Empty inventory for testing.
def empty_inventory(self):
return {'_meta': {'hostvars': {}}}
# Read the command line args passed to the script.
def read_cli_args(self):
parser = argparse.ArgumentParser()
parser.add_argument('--list', action = 'store_true')
parser.add_argument('--host', action = 'store')
self.args = parser.parse_args()
# Get the inventory.
ExampleInventory()