-
Notifications
You must be signed in to change notification settings - Fork 18
/
inventory.py
executable file
·216 lines (167 loc) · 7.22 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 confirm IT solutions
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import os
import sys
import yaml
import json
import re
from subprocess import check_call
from argparse import ArgumentParser
from tempfile import mkdtemp
from shutil import rmtree
class AnsibleGitInventory(object):
'''
Class to read a YAML from a git repository and generate a valid Ansible
dynamic inventory output.
Please use this class within a with-block or call the cleanup() method
manually when you're finished.
'''
def __init__(self):
'''
Class constructor which creates the temporary working directory.
'''
self.working_dir = mkdtemp()
def __enter__(self):
'''
Returns the instance pointer when with-context is entered.
'''
return self
def __exit__(self, exc_type, exc_value, traceback):
'''
Wrapper to call cleanup() when with-context is exited.
'''
self.cleanup()
def cleanup(self):
'''
Removes the temporary working directory and therefor all generated
data on the filesystem.
'''
if os.path.isdir(self.working_dir):
rmtree(self.working_dir)
def clone_repository(self, url, commit=None, sshkey=None):
'''
Clone git repository into a temporary working directory.
To specify a specific commit branch or tag you can use the `commit`
argument. If you want to use an alternative SSH key define the
`sshkey` argument.
'''
if sshkey:
os.environ['GIT_SSH_COMMAND'] = 'ssh -i ' + sshkey
command = ['git', 'clone', '-q']
if commit:
command.extend(['-b', commit])
command.append(url)
command.append(self.working_dir)
check_call(command)
def parse_inventory(self, path):
inventory = os.path.join(self.working_dir, path)
name = os.path.basename(inventory).split('.')[0]
if not os.path.isfile(inventory):
raise IOError('Inventory file "{}" not found in repository'.format(path))
# Read inventory file.
with open(inventory, 'r') as f:
# Parse YAML.
data = yaml.load(f)
# Prepare result dict.
result = {
'_meta': {
'hostvars': {}
},
name: {
'children': []
}
}
# Loop through inventory YAML and build result yaml.
for tier, group in data.iteritems():
# Build group name for inv-tier.
inv_tier = '{0}-{1}'.format(name, tier)
# Create empty tier & inv-tier groups.
result[tier] = {
'children': []
}
result[inv_tier] = {
'children': [tier]
}
# Add tier to inv group.
result[name]['children'].append(tier)
for loc, hosts in group.iteritems():
# Build group names for tier-loc, inv-loc and inv-tier-loc.
tier_loc = '{0}-{1}'.format(tier, loc)
inv_loc = '{0}-{1}'.format(name, loc)
inv_tier_loc = '{0}-{1}'.format(name, tier_loc)
# Add tier-loc to tier group.
result[tier]['children'].append(tier_loc)
# Add tier-loc to inv-loc group.
if inv_loc not in result:
result[inv_loc] = {
'children': []
}
result[inv_loc]['children'].append(tier_loc)
# Add inv-loc to loc group.
if loc not in result:
result[loc] = {
'children': [inv_loc]
}
elif inv_loc not in result[loc]['children']:
result[loc]['children'].append(inv_loc)
# Create tier-loc and inv-tier-loc groups.
result[tier_loc] = {
'hosts': hosts
}
result[inv_tier_loc] = {
'children': [tier_loc]
}
return json.dumps(obj=result, sort_keys=True, indent=4, separators=(',', ': '))
if __name__ == '__main__':
#
# Get arguments from CLI or via environment variables.
#
# We need to do that because the Tower can't pass any CLI arguments to a
# dynamic inventory script. Therefor environment variables must be used.
#
if 'URL' in os.environ and 'INVENTORY' in os.environ and os.environ['URL'] and os.environ['INVENTORY']:
kwargs_clone = {
'url': os.environ['URL'],
}
inventory = os.environ['INVENTORY']
if 'SSHKEY' in os.environ:
kwargs_clone['sshkey'] = os.environ['SSHKEY']
if 'COMMIT' in os.environ:
kwargs_clone['commit'] = os.environ['COMMIT']
else:
# Parse CLI arguments.
parser = ArgumentParser(description='Ansible inventory script')
parser.add_argument('--sshkey', help='Path to an alternative SSH private key', type=str)
parser.add_argument('--commit', help='Commit to checkout (e.g. branch or tag)', type=str)
parser.add_argument('url', help='URL of the git repository', type=str)
parser.add_argument('inventory', help='Path of the inventory file', type=str)
args = parser.parse_args()
kwargs_clone = {
'url': args.url,
'sshkey': args.sshkey,
'commit': args.commit,
}
inventory = args.inventory
#
# Clone repository and parse inventory file.
#
try:
with AnsibleGitInventory() as obj:
# Clone repository.
obj.clone_repository(**kwargs_clone)
# Parse inventory.
data = obj.parse_inventory(path=inventory)
# Print inventory JSON and exit.
sys.stdout.write(data + '\n')
sys.stdout.flush()
sys.exit(0)
except Exception, e:
sys.stderr.write(str(e) + '\n')
sys.stderr.flush()
sys.exit(1)