Skip to content

Instantly share code, notes, and snippets.

@a-tal
Created June 6, 2018 14:12
Show Gist options
  • Save a-tal/3a4a54ccc3c98f4e0a7aa6434f5fdc99 to your computer and use it in GitHub Desktop.
Save a-tal/3a4a54ccc3c98f4e0a7aa6434f5fdc99 to your computer and use it in GitHub Desktop.
kube merge configs
"""Merge or unmerge kubernetes config files.
Usage:
kube_merge_configs.py [options] <conf_yaml>
Options:
--unmerge, -u Remove the input file from your main config
--noop Don't write the main config, dump to stdout
"""
import os
import yaml
from docopt import docopt
MERGE_KEYS = ("clusters", "contexts", "users")
def config_plus(config, new_config):
"""Add the new config values to the existing config."""
for key in MERGE_KEYS:
for item in new_config[key]:
if item not in config[key]:
config[key].append(item)
def config_minus(config, new_config):
"""Remove the new config values from the existing config."""
for key in MERGE_KEYS:
for item in new_config[key]:
config[key].remove(item)
def main():
"""Command line entry point."""
args = docopt(__doc__, version="kube_merge_configs.py 0.0.1")
if not os.path.isfile(args["<conf_yaml>"]):
raise SystemExit("conf_yaml {} not found".format(args["<conf_yaml>"]))
try:
with open(args["<conf_yaml>"], "r") as openconf:
new_conf = yaml.load(openconf.read())
except Exception as error:
raise SystemExit("could not load new config: {!r}".format(error))
conf_path = os.path.join(os.path.expanduser("~"), ".kube", "config")
try:
with open(conf_path, "r") as openconf:
config = yaml.load(openconf.read())
except Exception as error:
raise SystemExit("could not load default config: {!r}".format(error))
if args["--unmerge"]:
config_minus(config, new_conf)
else:
config_plus(config, new_conf)
config_str = yaml.dump(config, default_flow_style=False, indent=2).strip()
if args["--noop"]:
print(config_str)
else:
with open(conf_path, "w") as openconf:
openconf.write(config_str)
print("merged {} into kube config at {}".format(
args["<conf_yaml>"],
conf_path,
))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment