import json import pyinputplus as pyip from jinja2 import Environment, PackageLoader, select_autoescape # Get clusters from json config with open("clusters.json") as json_file: CLUSTERS = json.load(json_file)["clusters"] # Setup Jinja2 jin = Environment(loader=PackageLoader("n-gen"), autoescape=select_autoescape()) # ID of next config - TBD - read this from list of configs and increment! CONF_ID = 1 def get_domains(): new_domain = True domains = [] while new_domain: domain = pyip.inputStr("Enter a full domain name: ") domains.append(domain) next_domain = pyip.inputYesNo("Do you want to add another domain? (y/n) ") if next_domain == "no": new_domain = False return domains def get_upstreams(clusters): print("\nNow, we will select upstream server(s).") if ( pyip.inputYesNo( "Is the service located on existing upstream cluster (like Swarm)? (y/n) " ) == "yes" ): cluster_list = [d["name"] for d in clusters] sel_cluster_name = pyip.inputMenu(cluster_list, lettered=True, blank=True) cluster = [ element for element in clusters if element["name"] == sel_cluster_name ][0] print("Selected cluster " + cluster["name"] + " with nodes:") for node in cluster["nodes"]: print(node) return cluster["nodes"] else: new_upstream = True upstreams = [] while new_upstream: upstream = pyip.inputStr("Enter IPv4 address of one upstream server: ") upstreams.append(upstream) next_upstream = pyip.inputYesNo( "Do you want to add another upstream server? (y/n) " ) if next_upstream == "no": new_upstream = False return upstreams def get_port(): return pyip.inputInt( "\nEnter a port number for the upstream servers: ", min=81, max=65534 ) def get_proto(): print("\nEnter the upstream protocol (between service and reverse proxy)") return pyip.inputMenu(["http://", "https://"], lettered=True) def input_check(domains, upstreams, port, proto): print("\n-----------------------------------------------") print("You have entered following service information:") print("Domains:") for domain in domains: print("\t" + domain) print("Upstream servers with proto and port:") for upstream in upstreams: print("\t" + proto + upstream + ":" + str(port)) if pyip.inputYesNo("Is this information correct? (y/n) ") == "yes": return True else: print("Sorry to hear that, please start again. Exiting") exit() def fill_template(id, domains, upstreams, port, proto): template = jin.get_template("nginx-site.conf") return template.render( id=id, domains=domains, upstreams=upstreams, port=port, proto=proto ) def main(): print("This script will generate nginx configuration and for new service.\n") domains = get_domains() upstreams = get_upstreams(CLUSTERS) port = get_port() proto = get_proto() input_check(domains, upstreams, port, proto) print(fill_template(CONF_ID, domains, upstreams, port, proto)) # def test(): # print(fill_template("1110", ['nolog.cz', 'www.nolog.cz'], ['10.0.0.1', '10.0.0.2'], 80, 'https://')) if __name__ == "__main__": main() # test()