Giter Site home page Giter Site logo

kubectl-reap's Introduction

kubectl-reap

actions-workflow-test release codecov pkg.go.dev license

kubectl-reap is a kubectl plugin that deletes unused Kubernetes resources.

screencast

Supported resources:

Kind Condition
Pod Not running
ConfigMap Not referenced by any Pods or ReplicaSet
Secret Not referenced by any Pods, ReplicaSet, or ServiceAccounts
PersistentVolume Not satisfying any PersistentVolumeClaims
PersistentVolumeClaim Not referenced by any Pods
Job Completed
PodDisruptionBudget Not targeting any Pods
HorizontalPodAutoscaler Not targeting any resources

Since this plugin supports dry-run as described below, it also helps you to find resources you misconfigured or forgot to delete.

Before getting started, read the caveats of using this plugin.

Installation

Download precompiled binaries from GitHub Releases.

Via Krew

$ kubectl krew install reap

Via Homebrew

$ brew tap micnncim/kubectl-reap https://github.com/micnncim/kubectl-reap
$ brew install kubectl-reap

Via Go

$ go get github.com/micnncim/kubectl-reap/cmd/kubectl-reap

Examples

Pods

In this example, this plugin deletes all Pods whose status is not Running.

$ kubectl get po
NAME          READY   STATUS      RESTARTS   AGE
pod-running   1/1     Running     0          10s
pod-pending   0/1     Pending     0          20s
pod-failed    0/1     Failed      0          30s
pod-unknown   0/1     Unknown     0          40s
job-kqpxc     0/1     Completed   0          50s

$ kubectl reap po
pod/pod-pending deleted
pod/pod-failed deleted
pod/pod-unknown deleted
pod/job-kqpxc deleted

ConfigMaps

In this example, this plugin deletes the unused ConfigMap config-2.

$ kubectl get cm
NAME       DATA   AGE
config-1   1      0m15s
config-2   1      0m10s

$ cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - name: nginx
    image: nginx
    volumeMounts:
    - name: config-1-volume
      mountPath: /var/config
  volumes:
  - name: config-1-volume
    configMap:
      name: config-1
EOF

$ kubectl reap cm
configmap/config-2 deleted

Interactive Mode

You can choose which resource you will delete one by one by interactive mode.

$ kubectl reap cm --interactive # or '-i'
? Are you sure to delete configmap/config-1? Yes
configmap/config-1 deleted
? Are you sure to delete configmap/config-2? No
? Are you sure to delete configmap/config-3? Yes
configmap/config-3 deleted

Usage

$ kubectl reap --help

Delete unused resources. Supported resources:

- Pods (whose status is not Running)
- ConfigMaps (not used by any Pods)
- Secrets (not used by any Pods or ServiceAccounts)
- PersistentVolumes (not satisfying any PersistentVolumeClaims)
- PersistentVolumeClaims (not used by any Pods)
- Jobs (completed)
- PodDisruptionBudgets (not targeting any Pods)
- HorizontalPodAutoscalers (not targeting any resources)

Usage:
  kubectl reap RESOURCE_TYPE [flags]

Examples:

  # Delete ConfigMaps not mounted on any Pods and in the current namespace and context
  $ kubectl reap configmaps

  # Delete unused ConfigMaps and Secrets in the namespace/my-namespace and context/my-context
  $ kubectl reap cm,secret -n my-namespace --context my-context

  # Delete ConfigMaps not mounted on any Pods and across all namespace
  $ kubectl reap cm --all-namespaces

  # Delete Pods whose status is not Running as client-side dry-run
  $ kubectl reap po --dry-run=client

Flags:
  -A, --all-namespaces                 If true, delete the targeted resources across all namespace except kube-system
      --allow-missing-template-keys    If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. (default true)
      --as string                      Username to impersonate for the operation
      --as-group stringArray           Group to impersonate for the operation, this flag can be repeated to specify multiple groups.
      --cache-dir string               Default cache directory (default "/Users/micnncim/.kube/cache")
      --certificate-authority string   Path to a cert file for the certificate authority
      --client-certificate string      Path to a client certificate file for TLS
      --client-key string              Path to a client key file for TLS
      --cluster string                 The name of the kubeconfig cluster to use
      --context string                 The name of the kubeconfig context to use
      --dry-run string[="unchanged"]   Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. (default "none")
      --field-selector string          Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type.
      --force                          If true, immediately remove resources from API and bypass graceful deletion. Note that immediate deletion of some resources may result in inconsistency or data loss and requires confirmation.
      --grace-period int               Period of time in seconds given to the resource to terminate gracefully. Ignored if negative. Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion). (default -1)
  -h, --help                           help for kubectl
      --insecure-skip-tls-verify       If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure
  -i, --interactive                    If true, a prompt asks whether resources can be deleted
      --kubeconfig string              Path to the kubeconfig file to use for CLI requests.
  -n, --namespace string               If present, the namespace scope for this CLI request
  -o, --output string                  Output format. One of: json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-as-json|jsonpath-file.
  -q, --quiet                          If true, no output is produced
      --request-timeout string         The length of time to wait before giving up on a single server request. Non-zero values should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests. (default "0")
  -l, --selector string                Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)
  -s, --server string                  The address and port of the Kubernetes API server
      --template string                Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
      --timeout duration               The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object
      --tls-server-name string         Server name to use for server certificate validation. If it is not provided, the hostname used to contact the server is used
      --token string                   Bearer token for authentication to the API server
      --user string                    The name of the kubeconfig user to use
  -v, --version                        If true, show the version of this plugin
      --wait                           If true, wait for resources to be gone before returning. This waits for finalizers.

Caveats

  • It's recommended to run this plugin as dry-run (--dry-run=client or --dry-run=server) first or interactive mode (--interactive) in order to examine what resources will be deleted when running it, especially when you're trying to run it in a production environment.
  • Even if you use --namespace kube-system or --all-namespaces, this plugin never deletes any resources in kube-system so that it prevents unexpected resource deletion.
  • This plugin doesn't determine whether custom controllers or CRDs consume or depend on the supported resources. Make sure the resources you want to reap aren't used by them.
    • e.g.) A Secret which isn't used by any Pods or ServiceAccounts but used by cert-manager can be deleted

Background

kubectl apply --prune allows us to delete unused resources. However, it's not very flexible when we want to choose what kind resource to be deleted. This plugin provides more flexible, easy way to delete resources.

Similar Projects

kubectl-reap's People

Contributors

dependabot[bot] avatar goreleaserbot avatar micnncim avatar tr3mor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

kubectl-reap's Issues

Cannot install on MacOS using brew

When I run brew install kubectl-reap the output is:

Error: micnncim/kubectl-reap/kubectl-reap: wrong number of arguments (given 1, expected 0)

Secrets used by Ingress not detected as in use

Ingress resources can use secrets to store TLS certificates, such as those managed by Cert Manager. Kubectl-reap currently detects these secrets are not in use and suggests removing them.

Eg

$ kubectl get secret
NAME                              TYPE                                  DATA   AGE
default-token-ggbbh               kubernetes.io/service-account-token   3      521d
review-41-enquiry-4r57wt-secret   Opaque                                3      10d
review-41-enquiry-4r57wt-tls      kubernetes.io/tls                     3      10d

#The review-41-enquiry-4r57wt-secret is used by a pod

$ kubectl reap secret --dry-run=client
secret/review-41-enquiry-4r57wt-tls deleted (dry run)

$ kubectl get ingress review-41-enquiry-4r57wt -o yaml 
#partly redacted
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-prod
    kubernetes.io/ingress.class: nginx
    kubernetes.io/tls-acme: "true"
spec:
  rules:
  - host: 41-enquiry.example.com
    http:
      paths:
      - backend:
          service:
            name: review-41-enquiry-4r57wt
            port:
              number: 8000
        path: /
        pathType: Prefix
  tls:
  - hosts:
    - 41-enquiry.example.com
    secretName: review-41-enquiry-4r57wt-tls

Cannot install it on MacOS

Hi, I'm trying to use your tool however, I'm unable with all the suggested ways in the readme.

Krew, I can see it in the list already however:

kubectl krew install reap          
Updated the local copy of plugin index.
Installing plugin: reap
W1025 14:03:40.703125   98490 install.go:164] failed to install plugin "reap": plugin "reap" does not offer installation for this platform
failed to install some plugins: [reap]: plugin "reap" does not offer installation for this platform

brew gives the following error Error: kubectl-reap: wrong number of arguments (given 1, expected 0) on three different machines.

is this still maintained? Thank you

ConfigMaps in CronJobs Env are not detected as in use

(Similiar to #120)

I've found that ConfigMaps used by CronJobs for eg. env vars are not detected as in-use.

apiVersion: batch/v1
kind: CronJob
metadata:
  name: test
spec:
  jobTemplate:
    spec:
      template:
        spec:
          containers:
            - env:
                - name: TEST
                  valueFrom:
                    configMapKeyRef:
                      key: TEST
                      name: test-config

Output from kubectl reap cm:

configmap/test-config deleted

Apply precaution when handling kube-system namespace

kubectl prune configmap --all-namespaces --dry-run=client
configmap/object-bucket-claim deleted (dry run)
configmap/helm-operator-kube-config deleted (dry run)
configmap/skyblock deleted (dry run)
configmap/cluster-info deleted (dry run)
configmap/cert-manager-cainjector-leader-election deleted (dry run)
configmap/cert-manager-cainjector-leader-election-core deleted (dry run)
configmap/cert-manager-controller deleted (dry run)
configmap/extension-apiserver-authentication deleted (dry run)
configmap/kubeadm-config deleted (dry run)
configmap/kubelet-config-1.18 deleted (dry run)
configmap/linkerd-config-addons deleted (dry run)
configmap/bungee-op-lock deleted (dry run)
configmap/nslock-op-lock deleted (dry run)
configmap/object-bucket-claim deleted (dry run)
configmap/server-op-lock deleted (dry run)
configmap/sftp-op-lock deleted (dry run)
configmap/config deleted (dry run)
configmap/prom-operator-grafana-test deleted (dry run)
configmap/prom-operator-prometheus-o-apiserver deleted (dry run)
configmap/prom-operator-prometheus-o-cluster-total deleted (dry run)
configmap/prom-operator-prometheus-o-controller-manager deleted (dry run)
configmap/prom-operator-prometheus-o-etcd deleted (dry run)
configmap/prom-operator-prometheus-o-grafana-datasource deleted (dry run)
configmap/prom-operator-prometheus-o-k8s-coredns deleted (dry run)
configmap/prom-operator-prometheus-o-k8s-resources-cluster deleted (dry run)
configmap/prom-operator-prometheus-o-k8s-resources-namespace deleted (dry run)
configmap/prom-operator-prometheus-o-k8s-resources-node deleted (dry run)
configmap/prom-operator-prometheus-o-k8s-resources-pod deleted (dry run)
configmap/prom-operator-prometheus-o-k8s-resources-workload deleted (dry run)
configmap/prom-operator-prometheus-o-k8s-resources-workloads-namespace deleted (dry run)
configmap/prom-operator-prometheus-o-kubelet deleted (dry run)
configmap/prom-operator-prometheus-o-namespace-by-pod deleted (dry run)
configmap/prom-operator-prometheus-o-namespace-by-workload deleted (dry run)
configmap/prom-operator-prometheus-o-node-cluster-rsrc-use deleted (dry run)
configmap/prom-operator-prometheus-o-node-rsrc-use deleted (dry run)
configmap/prom-operator-prometheus-o-nodes deleted (dry run)
configmap/prom-operator-prometheus-o-persistentvolumesusage deleted (dry run)
configmap/prom-operator-prometheus-o-pod-total deleted (dry run)
configmap/prom-operator-prometheus-o-prometheus deleted (dry run)
configmap/prom-operator-prometheus-o-proxy deleted (dry run)
configmap/prom-operator-prometheus-o-scheduler deleted (dry run)
configmap/prom-operator-prometheus-o-statefulset deleted (dry run)
configmap/prom-operator-prometheus-o-workload-total deleted (dry run)
configmap/ingress-controller-leader-nginx deleted (dry run)
configmap/nginx-nginx-ingress-tcp deleted (dry run)
configmap/ceph-delete-bucket deleted (dry run)
configmap/object-bucket-claim deleted (dry run)
configmap/local-device-amd1 deleted (dry run)
configmap/local-device-amd2 deleted (dry run)
configmap/local-device-s1 deleted (dry run)
configmap/local-device-s2 deleted (dry run)
configmap/local-device-s3 deleted (dry run)
configmap/rook-ceph-operator-config deleted (dry run)
configmap/rook-ceph-pdbstatemap deleted (dry run)

Ran it as a test. Looks useful and I know that this is the purpose of dry-run. Though I'd say when using --all-namespaces some kube-system default config maps should be ignored least. Specifically:

configmap/kubeadm-config deleted (dry run)
configmap/kubelet-config-1.18 deleted (dry run)

Calling bottle :unneeded is deprecated

Getting these warnings on every brew operation.

Warning: Calling bottle :unneeded is deprecated! There is no replacement.
Please report this issue to the micnncim/kubectl-reap tap (not Homebrew/brew or Homebrew/core):
  /usr/local/Homebrew/Library/Taps/micnncim/homebrew-kubectl-reap/Formula/kubectl-reap.rb:9

can not build on mac m1

$ go build cmd/kubectl-reap/main.go
...
go: downloading github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578
# golang.org/x/sys/unix
../../.asdf/installs/golang/1.19.1/packages/pkg/mod/golang.org/x/[email protected]/unix/syscall_darwin.1_13.go:29:3: //go:linkname must refer to declared function or variable
../../.asdf/installs/golang/1.19.1/packages/pkg/mod/golang.org/x/[email protected]/unix/zsyscall_darwin_arm64.1_13.go:27:3: //go:linkname must refer to declared function or variable
../../.asdf/installs/golang/1.19.1/packages/pkg/mod/golang.org/x/[email protected]/unix/zsyscall_darwin_arm64.1_13.go:40:3: //go:linkname must refer to declared function or variable
../../.asdf/installs/golang/1.19.1/packages/pkg/mod/golang.org/x/[email protected]/unix/zsyscall_darwin_arm64.go:28:3: //go:linkname must refer to declared function or variable
../../.asdf/installs/golang/1.19.1/packages/pkg/mod/golang.org/x/[email protected]/unix/zsyscall_darwin_arm64.go:43:3: //go:linkname must refer to declared function or variable
../../.asdf/installs/golang/1.19.1/packages/pkg/mod/golang.org/x/[email protected]/unix/zsyscall_darwin_arm64.go:59:3: //go:linkname must refer to declared function or variable
../../.asdf/installs/golang/1.19.1/packages/pkg/mod/golang.org/x/[email protected]/unix/zsyscall_darwin_arm64.go:75:3: //go:linkname must refer to declared function or variable
../../.asdf/installs/golang/1.19.1/packages/pkg/mod/golang.org/x/[email protected]/unix/zsyscall_darwin_arm64.go:90:3: //go:linkname must refer to declared function or variable
../../.asdf/installs/golang/1.19.1/packages/pkg/mod/golang.org/x/[email protected]/unix/zsyscall_darwin_arm64.go:105:3: //go:linkname must refer to declared function or variable
../../.asdf/installs/golang/1.19.1/packages/pkg/mod/golang.org/x/[email protected]/unix/zsyscall_darwin_arm64.go:121:3: //go:linkname must refer to declared function or variable
../../.asdf/installs/golang/1.19.1/packages/pkg/mod/golang.org/x/[email protected]/unix/zsyscall_darwin_arm64.go:121:3: too many errors

stop not Running pods by scale deployment

what is the purpose of removing pods?
Do they have to start successful after deletion ?
If pod in pending waiting some resource, it won't help it
if pod in CrashLoopBackOff status , it won't help it

What do you think about to add scaling deployment of such notworking pods to 0 ?

Error from server (Expired)

This works for small cluster but failed for a large cluster, in this case, there were more than 5.5k HPA

$ kubectl reap hpa --all-namespaces --dry-run=client -ojson | jq -s . | jq -r '["NAMESPACE","HPA_NAME","CREATION_TIMESTAMP","LAST_USED_TIMESTAMP"],(.[] | [.metadata.namespace, .metadata.name, .metadata.creationTimestamp, .status.lastScaleTime]) | @tsv' | column -ts $'\t' 

Error from server (Expired): The provided continue parameter is too old to display a consistent list result. You can start a new list without the continue parameter, or use the continue token in this response to retrieve the remainder of the results. Continuing with the provided token results in an inconsistent list - objects that were created, modified, or deleted between the time the first chunk was returned and now may show up in the list.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.