2022-06-12 22:36:35 +02:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
"""
|
|
|
|
Create a dynamic inventory for this ansible playbook
|
|
|
|
"""
|
|
|
|
import socket
|
|
|
|
import sys
|
2022-06-18 13:16:59 +02:00
|
|
|
import json
|
2022-06-12 22:36:35 +02:00
|
|
|
|
|
|
|
# create a dict to match hostnames to enviroments
|
|
|
|
env_dict = {
|
|
|
|
'work':
|
|
|
|
['workstation.local'],
|
|
|
|
'private':
|
|
|
|
['dderpy.local', 'foo.bar']
|
|
|
|
}
|
|
|
|
|
|
|
|
def fqdn():
|
|
|
|
"""
|
|
|
|
return fully qualified domain name
|
|
|
|
"""
|
|
|
|
return socket.getfqdn()
|
|
|
|
|
|
|
|
def env(domain):
|
|
|
|
"""
|
|
|
|
map a hostname to a space
|
|
|
|
"""
|
|
|
|
for key, values in env_dict.items():
|
|
|
|
if domain in values:
|
|
|
|
return key
|
2022-06-18 13:16:59 +02:00
|
|
|
print(json.dumps(empty_host_list(), sort_keys=True, indent=2))
|
|
|
|
sys.exit()
|
2022-06-12 22:36:35 +02:00
|
|
|
|
2022-06-18 13:16:59 +02:00
|
|
|
def empty_host_list():
|
|
|
|
"""
|
|
|
|
return empty host list
|
|
|
|
"""
|
|
|
|
comment = "No valid host found. returning empty host list!"
|
|
|
|
return json.loads('{"_meta": {"comment": "' + comment +
|
|
|
|
'", "hostvars": {}}, "instances": {"hosts": []}}')
|
2022-06-12 22:36:35 +02:00
|
|
|
|
|
|
|
def main():
|
|
|
|
"""
|
|
|
|
main funktion
|
|
|
|
will analyse on which host this script is started
|
|
|
|
and will print the dynamic inventory to tell ansible
|
|
|
|
which host_vars and group_vars should be used
|
|
|
|
"""
|
|
|
|
host = fqdn()
|
|
|
|
group = env(host)
|
|
|
|
print(host + group)
|
2022-06-18 13:16:59 +02:00
|
|
|
#{
|
|
|
|
# "_meta": {
|
|
|
|
# "hostvars": { }
|
|
|
|
# },
|
|
|
|
#
|
|
|
|
# "instances": {
|
|
|
|
# "hosts": ["10.66.70.33"]
|
|
|
|
# }
|
2022-06-12 22:36:35 +02:00
|
|
|
# }
|
|
|
|
|
|
|
|
main()
|