75 lines
2.0 KiB
Python
75 lines
2.0 KiB
Python
"""Script to add a domain without tht "www" and force redirect to www with TLS
|
|
|
|
To apply the changes to the cluster, you can use the following command:
|
|
|
|
kubectl -n <NAMESPACE> apply -f <(python add-domain.py)
|
|
|
|
|
|
"""
|
|
|
|
import os
|
|
import subprocess
|
|
|
|
import yaml
|
|
|
|
|
|
def get_ingress(ns: str, name: str) -> dict:
|
|
"""Get the ingress object from the cluster"""
|
|
process = subprocess.Popen(
|
|
["kubectl", "get", "ingress", "-n", ns, name, "-o", "yaml"],
|
|
stdout=subprocess.PIPE,
|
|
)
|
|
stdout, _ = process.communicate()
|
|
return yaml.safe_load(stdout)
|
|
|
|
|
|
def tranform(name: str, ns: str, domain: str) -> dict:
|
|
"""Return the transformed ingress object"""
|
|
|
|
# get the ingress content
|
|
ingress = get_ingress(ns, name)
|
|
|
|
# remove all nginx annotations
|
|
ingress["metadata"]["annotations"] = {
|
|
k: v for k, v in ingress["metadata"]["annotations"].items() if "nginx" not in k
|
|
}
|
|
|
|
# change the name of the ingress
|
|
ingress["metadata"]["name"] = f"{name}-redirect"
|
|
|
|
# add nginx.ingress.kubernetes.io/permanent-redirect annotation
|
|
ingress["metadata"]["annotations"].update(
|
|
{"nginx.ingress.kubernetes.io/permanent-redirect": f"https://www.{domain}"}
|
|
)
|
|
|
|
# change hostname
|
|
ingress["spec"]["tls"][0]["hosts"] = [domain]
|
|
ingress["spec"]["rules"][0]["host"] = domain
|
|
|
|
# change the secret name
|
|
ingress["spec"]["tls"][0]["secretName"] = f"{name}-redirect"
|
|
|
|
# cleanup the metadata
|
|
ingress.pop("status")
|
|
to_remove = [
|
|
"creationTimestamp",
|
|
"generation",
|
|
"resourceVersion",
|
|
"selfLink",
|
|
"uid",
|
|
]
|
|
for meta in to_remove:
|
|
ingress["metadata"].pop(meta) if meta in ingress["metadata"] else None
|
|
|
|
# print the new yaml content
|
|
return ingress
|
|
|
|
|
|
if __name__ == "__main__":
|
|
name = os.getenv("NAME", "website-server") # name of the ingress
|
|
ns = os.getenv("NAMESPACE", "katenary") # namespace
|
|
domain = os.getenv("DOMAIN", "katenary.io") # domain name without www
|
|
transformed = tranform(name, ns, domain)
|
|
|
|
print(yaml.dump(transformed))
|