|
#!/usr/bin/python3 |
|
|
|
import argparse |
|
import ngrok |
|
|
|
from os import getenv as environ |
|
|
|
# ngrok api configuration |
|
ngrok_api_url = "https://api.ngrok.com" |
|
ngrok_auth_token = environ("NGROK_AUTH_TOKEN") |
|
ngrok_client = ngrok.Client(ngrok_auth_token) |
|
|
|
# argument parser |
|
parser = argparse.ArgumentParser(description="Update haproxy based ngrok config") |
|
parser.add_argument("-c", |
|
"--config", action="store", |
|
default="/etc/haproxy/haproxy.cfg", |
|
help="HAProxy config path location", |
|
required=False, type=str) |
|
|
|
parser.add_argument("-s", |
|
"--source", action="store", |
|
default="tunnel.cfg.j2", |
|
help="Source template file", |
|
required=False, type=str) |
|
|
|
parser.add_argument("-n", |
|
"--name", action="store", |
|
default="tunnel", |
|
help="tunnel name that you want to activate", |
|
required=False, type=str) |
|
|
|
args = parser.parse_args() |
|
|
|
|
|
def get_tunnels() -> list: |
|
tunnels=list() |
|
for tunnel in ngrok_client.tunnels.list(): |
|
tunnels.append(tunnel.id) |
|
return tunnels |
|
|
|
|
|
def get_tunnel_addr(tunnel_id: int) -> (str, int): |
|
tunnel = ngrok_client.tunnels.get(tunnel_id) |
|
tunnel_addr = tunnel.public_url.split("tcp://")[1] |
|
tunnel_addr = tunnel_addr.split(":") |
|
return tunnel_addr[0], int(tunnel_addr[1]) |
|
|
|
|
|
def main(): |
|
tunnel_name = args.name |
|
get_tunnel_id = get_tunnels()[0] |
|
tunnel_host, tunnel_port = get_tunnel_addr(get_tunnel_id) |
|
|
|
from jinja2 import Environment, FileSystemLoader |
|
env = Environment(loader=FileSystemLoader(".")) |
|
template = env.get_template(args.source) |
|
with open(args.config, "w") as config_file: |
|
config_file.write(template.render( |
|
name=args.name, |
|
host=tunnel_host, |
|
port=tunnel_port |
|
)) |
|
|
|
if __name__ == "__main__": |
|
main() |