Last active
April 20, 2018 00:18
-
-
Save mababio/1e11ab8704e8b0959865f36dfef4107f to your computer and use it in GitHub Desktop.
dynamic ansible inventory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import json | |
import sys | |
class foo: | |
def __init__(self): | |
self.json_inventory=[] | |
def get_ci_list(self): | |
# input --> file that lists ci machines --> return pyhton list of ci | |
# snowtool -L 10 --linux | |
with open('ci_list', "r") as f: | |
return f.read().splitlines() | |
#create json ansible group with passed arguments | |
def create_group(self,hostname,ip=None, ansible_ssh_user='unixsvc'): | |
if ip==None: | |
ip=hostname | |
result={} | |
app_name = hostname | |
result[app_name] = {} | |
result[app_name]['hosts'] = [] | |
result[app_name]['hosts'].append(hostname) | |
result[app_name]['vars'] = {} | |
result[app_name]['vars']['ansible_ssh_user'] = ansible_ssh_user | |
return str(result)[1:][:-1] | |
def append_group(self,group): | |
return self.json_inventory.append(group) | |
def get_json_inventory(self): | |
for item in self.get_ci_list(): | |
self.append_group(self.create_group(item)) | |
i = json.dumps( self.json_inventory,indent=4, separators=(',', ': '))[1:][:-1] | |
i= '{'+i+'}' | |
return i.replace('"','') | |
def test(self): | |
app_name ='35.153.120.42' | |
result={} | |
result[app_name] = {} | |
result[app_name]['hosts'] = [] | |
result[app_name]['hosts'].append('35.153.120.42') | |
result[app_name]['vars'] = {} | |
result[app_name]['vars']['ansible_ssh_user'] = 'bitnami' | |
print json.dumps( result,indent=4, separators=(',', ': ')) | |
def main(): | |
obj = foo() | |
print (obj.get_json_inventory()) | |
if __name__ == "__main__": | |
if len(sys.argv) == 2 and sys.argv[1] == '--list': | |
main() | |
elif len(sys.argv) == 3 and sys.argv[1] == '--host': | |
print(json.dumps({})) | |
else: | |
print("Need an argument, either --list or --host <host>") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment