#!/usr/bin/env python3 import yaml import os import argparse import sys def main(): parser = argparse.ArgumentParser(description="Get kubeconfig") parser.add_argument("--file", help="File to be added to kubeconfig", required=True) parser.add_argument("--name", help="Name of the cluster", required=True) args = parser.parse_args() new_file = args.file name = args.name kube_config_dir = os.path.join(os.environ["HOME"], ".kube") kube_config_file = os.path.join(kube_config_dir, "config") current_config = {} new_config = {} if not os.path.isdir(kube_config_dir): os.mkdir(kube_config_dir) if os.path.isfile(kube_config_file): with open(kube_config_file, "r") as f: current_config = yaml.safe_load(f) if "clusters" not in current_config: current_config["clusters"] = [] if "contexts" not in current_config: current_config["contexts"] = [] if "users" not in current_config: current_config["users"] = [] if new_file == "-": new_config = yaml.safe_load(sys.stdin.read()) elif os.path.isfile(new_file): with open(new_file, "r") as f: new_config = yaml.safe_load(f) else: raise Exception(f"Invalid file: {new_file}") if "clusters" in new_config: new_config["clusters"][0]["name"] = name current_config["clusters"] += new_config["clusters"] if "contexts" in new_config: new_config["contexts"][0]["name"] = name new_config["contexts"][0]["context"]["cluster"] = name new_config["contexts"][0]["context"]["user"] = name current_config["contexts"] += new_config["contexts"] if "users" in new_config: new_config["users"][0]["name"] = name current_config["users"] += new_config["users"] with open(kube_config_file, "w") as f: yaml.dump(current_config, f) if __name__ == "__main__": main()