Ephemeral port picker for LoadBalancer-type Kubernetes services in clusters with a single-address external address pool
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
1.3 KiB

  1. #!/usr/bin/env python3
  2. # "Have-A-Port" | ephemeral port picker for LoadBalancer-type Kubernetes services in clusters with a single-address external address pool
  3. from kubernetes import client, config
  4. import sys, random
  5. SVC_TYPE = 'LoadBalancer'
  6. def getopts():
  7. """parse command-line"""
  8. from optparse import OptionParser, OptionValueError
  9. usage = "%prog [options]"
  10. parser = OptionParser(usage=usage)
  11. parser.add_option("-n", "--count", type="int", default=1, dest="port_count", help="number of ports needed (default: %default)")
  12. return parser.parse_args()
  13. options, args = getopts()
  14. # load client configuration (kubeconfig)
  15. config.load_kube_config()
  16. # establish API connection
  17. connection = client.CoreV1Api()
  18. # query service objects
  19. all_services = connection.list_service_for_all_namespaces(watch=False)
  20. # determine ports in use
  21. ports_per_svc = [ svc.spec.ports for svc in all_services.items if svc.spec.type == SVC_TYPE]
  22. used_ports = [svc_port.port for svc_ports in ports_per_svc for svc_port in svc_ports]
  23. # determine available ports
  24. full_port_range = range(49152, 65536) # https://tools.ietf.org/html/rfc6335#section-8.1.2
  25. available_ports = list(set(full_port_range) - set(used_ports))
  26. # pick available ports
  27. print(' '.join(map(str, random.sample(available_ports, options.port_count))))