Skip to content

Instantly share code, notes, and snippets.

@luopio
Last active May 17, 2023 14:11
Show Gist options
  • Save luopio/e4887e9f54fee0b773a6f386d8d571ea to your computer and use it in GitHub Desktop.
Save luopio/e4887e9f54fee0b773a6f386d8d571ea to your computer and use it in GitHub Desktop.
"""
Quick and dirty yaml conversion to move from old style k8s Ingresses to
newer 1.22 style.
Requires pyyaml installed.
Absolutely no guarantees are given on this being useful. Usage:
> python k8s_convert_ingress_to_v1.py some-ingresses.yaml
Once you are happy, just direct the output to a new file
> python k8s_convert_ingress_to_v1.py some-ingresses.yaml > new-ingresses.yaml
"""
import sys
try:
import yaml
except ImportError:
print("pyyaml is required. Please install with:")
print("> pip install pyyaml")
sys.exit(1)
if __name__ == "__main__":
try:
docs = yaml.load_all(open(sys.argv[1], "rt"), Loader=yaml.Loader)
except IndexError:
print("Usage: ./convert <YAML_FILE>")
sys.exit(1)
yaml_snippets = []
for doc in docs:
if not doc:
continue
if doc["kind"] != "Ingress":
continue
if "backend" in doc["spec"]:
doc["spec"]["defaultBackend"] = doc["spec"]["backend"]
del(doc["spec"]["backend"])
if "rules" not in doc["spec"]:
print(
f'✗ {doc["metadata"]["name"]} has no rules, skipping',
file=sys.stderr
)
continue # might happen with kustomize patched stub ingresses
for rule in doc["spec"]["rules"]:
for path in rule["http"]["paths"]:
backend = path["backend"]
if "service" in backend:
print(
f'✗ {doc["metadata"]["name"]} > {rule["host"]} has path already updated, skipping',
file=sys.stderr
)
continue # consider this already upgraded
backend["service"] = dict(name=backend["serviceName"])
path["pathType"] = "ImplementationSpecific"
port = backend["servicePort"]
if type(port) == int:
backend["service"]["port"] = dict(number=port)
else:
backend["service"]["port"] = dict(name=port)
del(backend["serviceName"])
del(backend["servicePort"])
doc["apiVersion"] = "networking.k8s.io/v1"
yaml_snippets.append(yaml.dump(doc))
print(
f'✓ {doc["metadata"]["name"]} processed',
file=sys.stderr
)
print("\n---\n\n".join(yaml_snippets))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment