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':
|
2022-07-06 18:13:26 +02:00
|
|
|
['workstation.local', 'daringdoo.local'],
|
2022-06-12 22:36:35 +02:00
|
|
|
'private':
|
2022-06-26 02:31:29 +02:00
|
|
|
['derpy.local', 'applejack.local']
|
2022-06-12 22:36:35 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
def fqdn():
|
|
|
|
"""
|
|
|
|
return fully qualified domain name
|
|
|
|
"""
|
2022-07-06 18:13:26 +02:00
|
|
|
hostname = socket.gethostname()
|
|
|
|
if '.' not in hostname:
|
|
|
|
hostname = f"{hostname}.local"
|
|
|
|
return str(hostname)
|
2022-06-12 22:36:35 +02:00
|
|
|
|
|
|
|
def env(domain):
|
|
|
|
"""
|
|
|
|
map a hostname to a space
|
2022-06-18 13:45:34 +02:00
|
|
|
or print empty list if no one matched and exit
|
2022-06-12 22:36:35 +02:00
|
|
|
"""
|
|
|
|
for key, values in env_dict.items():
|
|
|
|
if domain in values:
|
|
|
|
return key
|
2022-06-26 02:31:29 +02:00
|
|
|
print(json.dumps(empty_host_list(domain), sort_keys=True, indent=2))
|
2022-06-18 13:16:59 +02:00
|
|
|
sys.exit()
|
2022-06-12 22:36:35 +02:00
|
|
|
|
2022-06-26 02:31:29 +02:00
|
|
|
def empty_host_list(domain):
|
2022-06-18 13:16:59 +02:00
|
|
|
"""
|
|
|
|
return empty host list
|
|
|
|
"""
|
2022-06-26 02:31:29 +02:00
|
|
|
comment = f"No valid host found. Found '{domain}'. Return empty host list!"
|
2022-06-18 13:16:59 +02:00
|
|
|
return json.loads('{"_meta": {"comment": "' + comment +
|
|
|
|
'", "hostvars": {}}, "instances": {"hosts": []}}')
|
2022-06-12 22:36:35 +02:00
|
|
|
|
2022-06-18 13:45:34 +02:00
|
|
|
def formated_host_group_list(host, group):
|
|
|
|
"""
|
|
|
|
build inventory and return it
|
|
|
|
"""
|
|
|
|
# pylint: disable=line-too-long
|
|
|
|
return json.loads('{"_meta": {"hostvars": {}},"' + str(group) + '": {"hosts": ["' + str(host) + '"]},"instances": {"children": ["' + str(group) + '"]}}')
|
|
|
|
|
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)
|
2022-06-18 13:45:34 +02:00
|
|
|
print(json.dumps(formated_host_group_list(host, group), sort_keys=True, indent=2))
|
|
|
|
|
|
|
|
|
|
|
|
|
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()
|