commit 259b59265a98769e7d25382a90f081264bee3197 Author: William P Date: Fri Mar 20 19:04:48 2026 -0400 initial commit diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..23ac4e6 --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright 2026 William T. Peebles + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..a3f488d --- /dev/null +++ b/README.md @@ -0,0 +1,23 @@ +# K8S helper scripts + +This repo contains various k8s helper scripts I've created to reduce the burden of tedious tasks maintaining my kubernetes cluster. + +Most of them aren't too customizable by default (but certainly can be edited for your needs), there may be a limited amount of variable settings such as namespaces + +Most of my scripts are in Python since it's my go-to quick-and-dirty scripting language. Unless stated otherwise, the only dependency would be the [official Kubernetes Python library](https://github.com/kubernetes-client/python) which is available on [PyPI](https://pypi.org/project/kubernetes/) + +*Full disclosure: I do use Claude Code but mostly for debugging and cleaning up my spaghetti code after it's already written. +I like to write my own code for functionality but let AI make it reliable and look somewhat presentable :-)* + +### Disclaimer +**All these scripts are MIT licensed and are distributed with NO WARRANTY. I am not liable for anything that happens to your cluster and/or production environment** + +As a good practice, you should thoroughly review *any* script before running it in your environment. + +I do try to include a final confirmation prompt with proposed changes (especially when it comes to deleting resources), but you should never blindly trust some random guy on GitHub to do that (I know I wouldn't 😊) + +## Scripts + +| Script | Description | Notes +| ------ | ----------- | ----- +| [cleanup-velero-resource-labels.py](./cleanup-velero-restore-labels.py) | Cleans up the `velero.io/backup-name` and `velero.io/restore-name` labels given to resources restored by Velero. | Built to work cluster-wide but not difficult to have it scoped to a specific namespace. \ No newline at end of file diff --git a/cleanup-velero-restore-labels.py b/cleanup-velero-restore-labels.py new file mode 100644 index 0000000..b429877 --- /dev/null +++ b/cleanup-velero-restore-labels.py @@ -0,0 +1,125 @@ +from kubernetes import client, config + +config.load_kube_config() + +api_client = client.ApiClient() +core_api = client.CoreV1Api(api_client) +apis_api = client.ApisApi(api_client) + +all_resources = [] + +velero_restored_resources_to_clean = [] + +# Core API group (v1) +for r in core_api.get_api_resources().resources: + all_resources.append({ + "name": r.name, + "namespaced": r.namespaced, + "kind": r.kind, + "group": "", + "version": "v1", + }) + +# All named API groups (apps, batch, networking.k8s.io, etc.) +for group in apis_api.get_api_versions().groups: + group_version = group.preferred_version.group_version # e.g. "apps/v1" + group_name = group.name + try: + result = api_client.call_api( + f"/apis/{group_version}", "GET", + auth_settings=["BearerToken"], + response_type="V1APIResourceList", + _return_http_data_only=True, + ) + for r in result.resources: + all_resources.append({ + "name": r.name, + "namespaced": r.namespaced, + "kind": r.kind, + "group": group_name, + "version": group.preferred_version.version, + }) + except Exception as e: + print(f" [warn] skipped {group_version}: {e}") + +for resource in all_resources: + if "/" in resource["name"]: # skip subresources like pods/log + continue + + # Build list URL — omitting namespace prefix returns all namespaces for namespaced resources + if resource["group"] == "": + url = f"/api/{resource['version']}/{resource['name']}" + else: + url = f"/apis/{resource['group']}/{resource['version']}/{resource['name']}" + + try: + response = api_client.call_api( + url, "GET", + auth_settings=["BearerToken"], + response_type="object", + _return_http_data_only=True, + ) + items = response.get("items", []) + for item in items: + metadata = item.get("metadata", {}) + labels = metadata.get('labels') or {} + if ("velero.io/backup-name" in labels or "velero.io/restore-name" in labels) and metadata.get('namespace') != "velero": + velero_restored_resources_to_clean.append({ + "kind": resource['kind'], + "resource_name": resource['name'], + "group": resource['group'], + "version": resource['version'], + "name": metadata.get('name'), + "namespace": metadata.get('namespace'), + "uid": metadata.get('uid'), + "labels": labels, + }) + except Exception as e: + msg = str(e) + if "(404)" not in msg and "(405)" not in msg: + print(f"[warn] could not list {resource['name']}: {e}") + + +if velero_restored_resources_to_clean is not None: + print("The following resources have velero restore labels on them. Verify them and then choose to unlabel them \n") + for item in velero_restored_resources_to_clean: + print(f"{item['kind']}: {item['namespace']}/{item['name']}") + if item['labels'] is not None: + print(f" Labels: ") + for key, value in item['labels'].items(): + if (key == "velero.io/backup-name" or key == "velero.io/restore-name"): + print(f" {key}: {value}") + print("\n") + answer = input("Continue to unlabel? [y/n]") + if answer.strip().lower() != "y": + print("Aborted") + else: + for item in velero_restored_resources_to_clean: + if item["group"] == "": + if item["namespace"]: + url = f"/api/{item['version']}/namespaces/{item['namespace']}/{item['resource_name']}/{item['name']}" + else: + url = f"/api/{item['version']}/{item['resource_name']}/{item['name']}" + else: + if item["namespace"]: + url = f"/apis/{item['group']}/{item['version']}/namespaces/{item['namespace']}/{item['resource_name']}/{item['name']}" + else: + url = f"/apis/{item['group']}/{item['version']}/{item['resource_name']}/{item['name']}" + + patch_body = {"metadata": {"labels": { + "velero.io/backup-name": None, + "velero.io/restore-name": None, + }}} + + try: + api_client.call_api( + url, "PATCH", + auth_settings=["BearerToken"], + response_type="object", + _return_http_data_only=True, + header_params={"Content-Type": "application/merge-patch+json"}, + body=patch_body, + ) + print(f"Unlabeled {item['kind']}: {item['namespace']}/{item['name']}") + except Exception as e: + print(f"[error] failed to unlabel {item['kind']} {item['namespace']}/{item['name']}: {e}") \ No newline at end of file