A Babashka script to clean up Kubernetes resources associated with deleted Git branches.
This tool helps maintain clean Kubernetes clusters by automatically (it could be used from a CI pipeline) removing resources (deployments, statefulsets, services, ingresses) that were created for Git branches that no longer exist.
It works by:
- Checking Git repositories for existing branches
- Comparing with deployed resources in Kubernetes
- Cleaning up resources that correspond to deleted branches (assuming proper annotations and labels have already been set on kubernetes resources)
- Babashka
kubectl
with access to your clustergit
command line tooljq
command line tool (might be removed later)
- Clone this repository
- Make the script executable:
chmod u+x autoclean.bb
Create a configuration file in EDN format at ~/.config/autoclean-k8s/config.edn
:
{:repos
{"app1"
{:repo "[email protected]:org/app1.git"
:namespace "apps"
:labelselector {:get ["app=myapp"]
:delete {:labels ["app=myapp"]
:branch-label "branch"}}
:branch-annotation "gitbranch"
:resource-types ["deployments.apps" "statefulsets.apps"]
:branchprefix ""}}}
Configuration options:
repo
: Git SSH URLnamespace
: Kubernetes namespacelabelselector.get
: Labels to identify resources to checklabelselector.delete
: Labels for resources to deletelabels
: Base labels for resourcesbranch-label
: Label key containing branch name
branch-annotation
: Annotation key containing Git branch nameresource-types
: Types of Kubernetes resources to checkbranchprefix
: Optional prefix added to branch names
Run in simulation mode (default, no deletions):
./autoclean.bb
Run with actual deletions:
./autoclean.bb --simulation false
Use custom config file:
./autoclean.bb --config /path/to/config.edn
-
For each repository in the config:
- Clones/updates the Git repository
- Gets list of current branches
- Checks Kubernetes resources matching configured labels
- Identifies resources using branches that no longer exist
- Deletes matching resources (deployments, statefulsets, services, ingresses)
-
Resources are identified using:
- Namespace
- Label selectors
- Branch name (from annotation)
-
Deletion is performed using kubectl with label selectors
- Simulation mode enabled by default
- Detailed logging of all operations
- Confirmation of deletions in logs
- Resource timeout limits
- Error handling with descriptive messages
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.