├── .gitignore ├── .goreleaser.yml ├── LICENSE ├── README.md ├── cleanup.go ├── glide.lock ├── glide.yaml ├── install.sh ├── pkg └── config │ ├── config.go │ ├── prompt.go │ └── workqueue.go └── plugin.yaml /.gitignore: -------------------------------------------------------------------------------- 1 | /vendor 2 | dist 3 | -------------------------------------------------------------------------------- /.goreleaser.yml: -------------------------------------------------------------------------------- 1 | # This is an example goreleaser.yaml file with some sane defaults. 2 | # Make sure to check the documentation at http://goreleaser.com 3 | builds: 4 | - 5 | env: 6 | - CGO_ENABLED=0 7 | main: ./cleanup.go 8 | binary: cleanup 9 | archive: 10 | replacements: 11 | darwin: Darwin 12 | linux: Linux 13 | windows: Windows 14 | 386: i386 15 | amd64: x86_64 16 | snapshot: 17 | name_template: "{{ .Tag }}-next" 18 | changelog: 19 | sort: asc 20 | filters: 21 | exclude: 22 | - '^docs:' 23 | - '^test:' 24 | release: 25 | # Repo in which the release will be created. 26 | # Default is extracted from the origin remote URL. 27 | # github: 28 | # owner: ashleyschuett 29 | # name: kubeconfig-cleanup 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # kubeconfig-cleanup 2 | 3 | ## About 4 | 5 | ### Description 6 | A kubectl plugin to clean up your kubeconfig file 7 | 8 | ### Installation 9 | Add `kubeconfig-cleanup` to your `kubectl` plugins directory. For more information about how plugins are loaded, please see the [official documentation](https://kubernetes.io/docs/tasks/extend-kubectl/kubectl-plugins/). 10 | 11 | See [Releases](https://github.com/ashleyschuett/kubeconfig-cleanup/releases) for the latest release matching your OS. 12 | 13 | ```bash 14 | # Pick the right release, e.g. "v1.0.1 Linux x64" 15 | $ export BINARY=kubeconfig-cleanup_1.0.1_Linux_x86_64.tar.gz 16 | ``` 17 | 18 | Then run `install.sh` by either cloning this repository or directly downloading the script. 19 | 20 | **Note:** The script and plugin configuration is configured to use `~/.kube/plugins/kubeconfig-cleanup` as the plugin and installation folder. 21 | 22 | ```bash 23 | $ git clone https://github.com/ashleyschuett/kubeconfig-cleanup 24 | $ cd kubeconfig-cleanup 25 | 26 | # make sure the script it's executable 27 | $ chmod +x install.sh 28 | $ ./install.sh 29 | ``` 30 | 31 | Alternatively with curl: 32 | 33 | ```bash 34 | $ curl -LO https://raw.githubusercontent.com/ashleyschuett/kubeconfig-cleanup/master/install.sh 35 | 36 | # make sure the script it's executable 37 | $ chmod +x install.sh 38 | $ ./install.sh 39 | ``` 40 | 41 | ### Usage 42 | Parse through kubeconfig in default directory 43 | ``` 44 | kubectl plugin kubeconfig-cleanup 45 | ``` 46 | 47 | Parse through kubeconfig at custom location 48 | ``` 49 | kubectl plugin kubeconfig-cleanup --kubeconfig /custom/kubeconfig/location 50 | ``` 51 | -------------------------------------------------------------------------------- /cleanup.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/ashleyschuett/kubeconfig-cleanup/pkg/config" 5 | ) 6 | 7 | func main() { 8 | m := config.NewManager() 9 | m.Run() 10 | } 11 | -------------------------------------------------------------------------------- /glide.lock: -------------------------------------------------------------------------------- 1 | hash: 55fec13ae3a23a3e1e131be862fb77a72eee4a9277bdd604b000e710eabe9a50 2 | updated: 2018-07-01T11:32:54.664426126-04:00 3 | imports: 4 | - name: github.com/briandowns/spinner 5 | version: 5b875a9171af19dbde37e70a8fcbe2ebd7285e05 6 | - name: github.com/fatih/color 7 | version: 5b77d2a35fb0ede96d138fc9a99f5c9b6aef11b4 8 | - name: github.com/ghodss/yaml 9 | version: 73d445a93680fa1a78ae23a5839bad48f32ba1ee 10 | - name: github.com/gogo/protobuf 11 | version: c0656edd0d9eab7c66d1eb0c568f9039345796f7 12 | subpackages: 13 | - proto 14 | - sortkeys 15 | - name: github.com/golang/glog 16 | version: 44145f04b68cf362d9c4df2182967c2275eaefed 17 | - name: github.com/golang/protobuf 18 | version: 1643683e1b54a9e88ad26d98f81400c8c9d9f4f9 19 | subpackages: 20 | - proto 21 | - ptypes 22 | - ptypes/any 23 | - ptypes/duration 24 | - ptypes/timestamp 25 | - name: github.com/google/gofuzz 26 | version: 44d81051d367757e1c7c6a5a86423ece9afcf63c 27 | - name: github.com/googleapis/gnostic 28 | version: 0c5108395e2debce0d731cf0287ddf7242066aba 29 | subpackages: 30 | - OpenAPIv2 31 | - compiler 32 | - extensions 33 | - name: github.com/howeyc/gopass 34 | version: bf9dde6d0d2c004a008c27aaee91170c786f6db8 35 | - name: github.com/imdario/mergo 36 | version: 6633656539c1639d9d78127b7d47c622b5d7b6dc 37 | - name: github.com/json-iterator/go 38 | version: 13f86432b882000a51c6e610c620974462691a97 39 | - name: github.com/mattn/go-colorable 40 | version: efa589957cd060542a26d2dd7832fd6a6c6c3ade 41 | - name: github.com/mattn/go-isatty 42 | version: 6ca4dbf54d38eea1a992b3c722a76a5d1c4cb25c 43 | - name: github.com/spf13/pflag 44 | version: 4c012f6dcd9546820e378d0bdda4d8fc772cdfea 45 | - name: golang.org/x/crypto 46 | version: 81e90905daefcd6fd217b62423c0908922eadb30 47 | subpackages: 48 | - ssh/terminal 49 | - name: golang.org/x/net 50 | version: 1c05540f6879653db88113bc4a2b70aec4bd491f 51 | subpackages: 52 | - context 53 | - html 54 | - html/atom 55 | - http2 56 | - http2/hpack 57 | - idna 58 | - lex/httplex 59 | - websocket 60 | - name: golang.org/x/sys 61 | version: 95c6576299259db960f6c5b9b69ea52422860fce 62 | subpackages: 63 | - unix 64 | - windows 65 | - name: golang.org/x/text 66 | version: b19bf474d317b857955b12035d2c5acb57ce8b01 67 | subpackages: 68 | - secure/bidirule 69 | - transform 70 | - unicode/bidi 71 | - unicode/norm 72 | - name: golang.org/x/time 73 | version: f51c12702a4d776e4c1fa9b0fabab841babae631 74 | subpackages: 75 | - rate 76 | - name: gopkg.in/inf.v0 77 | version: 3887ee99ecf07df5b447e9b00d9c0b2adaa9f3e4 78 | - name: gopkg.in/yaml.v2 79 | version: 670d4cfef0544295bc27a114dbac37980d83185a 80 | - name: k8s.io/api 81 | version: 73d903622b7391f3312dcbac6483fed484e185f8 82 | subpackages: 83 | - admissionregistration/v1alpha1 84 | - admissionregistration/v1beta1 85 | - apps/v1 86 | - apps/v1beta1 87 | - apps/v1beta2 88 | - authentication/v1 89 | - authentication/v1beta1 90 | - authorization/v1 91 | - authorization/v1beta1 92 | - autoscaling/v1 93 | - autoscaling/v2beta1 94 | - batch/v1 95 | - batch/v1beta1 96 | - batch/v2alpha1 97 | - certificates/v1beta1 98 | - core/v1 99 | - events/v1beta1 100 | - extensions/v1beta1 101 | - imagepolicy/v1alpha1 102 | - networking/v1 103 | - policy/v1beta1 104 | - rbac/v1 105 | - rbac/v1alpha1 106 | - rbac/v1beta1 107 | - scheduling/v1alpha1 108 | - settings/v1alpha1 109 | - storage/v1 110 | - storage/v1alpha1 111 | - storage/v1beta1 112 | - name: k8s.io/apimachinery 113 | version: 302974c03f7e50f16561ba237db776ab93594ef6 114 | subpackages: 115 | - pkg/api/errors 116 | - pkg/api/meta 117 | - pkg/api/resource 118 | - pkg/apis/meta/v1 119 | - pkg/apis/meta/v1/unstructured 120 | - pkg/apis/meta/v1beta1 121 | - pkg/conversion 122 | - pkg/conversion/queryparams 123 | - pkg/fields 124 | - pkg/labels 125 | - pkg/runtime 126 | - pkg/runtime/schema 127 | - pkg/runtime/serializer 128 | - pkg/runtime/serializer/json 129 | - pkg/runtime/serializer/protobuf 130 | - pkg/runtime/serializer/recognizer 131 | - pkg/runtime/serializer/streaming 132 | - pkg/runtime/serializer/versioning 133 | - pkg/selection 134 | - pkg/types 135 | - pkg/util/clock 136 | - pkg/util/errors 137 | - pkg/util/framer 138 | - pkg/util/intstr 139 | - pkg/util/json 140 | - pkg/util/net 141 | - pkg/util/runtime 142 | - pkg/util/sets 143 | - pkg/util/validation 144 | - pkg/util/validation/field 145 | - pkg/util/wait 146 | - pkg/util/yaml 147 | - pkg/version 148 | - pkg/watch 149 | - third_party/forked/golang/reflect 150 | - name: k8s.io/client-go 151 | version: 23781f4d6632d88e869066eaebb743857aa1ef9b 152 | subpackages: 153 | - discovery 154 | - kubernetes 155 | - kubernetes/scheme 156 | - kubernetes/typed/admissionregistration/v1alpha1 157 | - kubernetes/typed/admissionregistration/v1beta1 158 | - kubernetes/typed/apps/v1 159 | - kubernetes/typed/apps/v1beta1 160 | - kubernetes/typed/apps/v1beta2 161 | - kubernetes/typed/authentication/v1 162 | - kubernetes/typed/authentication/v1beta1 163 | - kubernetes/typed/authorization/v1 164 | - kubernetes/typed/authorization/v1beta1 165 | - kubernetes/typed/autoscaling/v1 166 | - kubernetes/typed/autoscaling/v2beta1 167 | - kubernetes/typed/batch/v1 168 | - kubernetes/typed/batch/v1beta1 169 | - kubernetes/typed/batch/v2alpha1 170 | - kubernetes/typed/certificates/v1beta1 171 | - kubernetes/typed/core/v1 172 | - kubernetes/typed/events/v1beta1 173 | - kubernetes/typed/extensions/v1beta1 174 | - kubernetes/typed/networking/v1 175 | - kubernetes/typed/policy/v1beta1 176 | - kubernetes/typed/rbac/v1 177 | - kubernetes/typed/rbac/v1alpha1 178 | - kubernetes/typed/rbac/v1beta1 179 | - kubernetes/typed/scheduling/v1alpha1 180 | - kubernetes/typed/settings/v1alpha1 181 | - kubernetes/typed/storage/v1 182 | - kubernetes/typed/storage/v1alpha1 183 | - kubernetes/typed/storage/v1beta1 184 | - pkg/apis/clientauthentication 185 | - pkg/apis/clientauthentication/v1alpha1 186 | - pkg/version 187 | - plugin/pkg/client/auth/exec 188 | - rest 189 | - rest/watch 190 | - tools/auth 191 | - tools/bootstrap/token/api 192 | - tools/clientcmd 193 | - tools/clientcmd/api 194 | - tools/clientcmd/api/latest 195 | - tools/clientcmd/api/v1 196 | - tools/metrics 197 | - tools/reference 198 | - transport 199 | - util/cert 200 | - util/flowcontrol 201 | - util/homedir 202 | - util/integer 203 | - name: k8s.io/kubernetes 204 | version: 03d97e0f8fc73d4fc89561d940259cf443b3ac7b 205 | subpackages: 206 | - cmd/kubeadm/app/util/kubeconfig 207 | testImports: [] 208 | -------------------------------------------------------------------------------- /glide.yaml: -------------------------------------------------------------------------------- 1 | package: github.com/ashleyschuett/kubeconfig-cleanup 2 | import: 3 | - package: k8s.io/client-go 4 | version: ^7.0.0 5 | - package: k8s.io/kubernetes 6 | version: ^1.12.0-alpha.0 7 | - package: k8s.io/apimachinery 8 | - package: github.com/briandowns/spinner 9 | version: ^1.1.0 10 | - package: github.com/fatih/color 11 | version: ^1.7.0 12 | -------------------------------------------------------------------------------- /install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -euo pipefail 4 | 5 | # increase script verbosity with -x 6 | # set -euxo pipefail 7 | 8 | # version to fetch 9 | VERSION="v1.0.1" 10 | 11 | # download binary and plugin configuration 12 | curl -L -o cleanup_${VERSION}.tgz https://github.com/ashleyschuett/kubeconfig-cleanup/releases/download/${VERSION}/$BINARY 13 | curl -LO https://raw.githubusercontent.com/ashleyschuett/kubeconfig-cleanup/${VERSION}/plugin.yaml 14 | 15 | # extract binary 16 | tar zxvf cleanup_${VERSION}.tgz cleanup 17 | rm cleanup_${VERSION}.tgz 18 | 19 | # create corresponding plugin folder and move binary/configuration 20 | mkdir -p ~/.kube/plugins/kubeconfig-cleanup 21 | mv cleanup plugin.yaml ~/.kube/plugins/kubeconfig-cleanup 22 | -------------------------------------------------------------------------------- /pkg/config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | apierrors "k8s.io/apimachinery/pkg/api/errors" 8 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 9 | 10 | kubeconfigutil "k8s.io/kubernetes/cmd/kubeadm/app/util/kubeconfig" 11 | 12 | bootstrapapi "k8s.io/client-go/tools/bootstrap/token/api" 13 | "k8s.io/client-go/tools/clientcmd" 14 | clientcmdapi "k8s.io/client-go/tools/clientcmd/api" 15 | ) 16 | 17 | type Manager struct { 18 | Original *clientcmdapi.Config 19 | New *clientcmdapi.Config 20 | prompter *prompter 21 | path string 22 | workqueue chan ContextResult 23 | totalContexts int 24 | contextedValidated int 25 | } 26 | 27 | func NewManager() *Manager { 28 | path := getKubeconfigPath() 29 | config, err := clientcmd.LoadFromFile(path) 30 | if err != nil { 31 | fmt.Fprintln(os.Stderr, err) 32 | os.Exit(1) 33 | } 34 | 35 | ch := make(chan ContextResult) 36 | 37 | return &Manager{ 38 | config, 39 | config.DeepCopy(), 40 | NewPrompter(), 41 | path, 42 | ch, 43 | len(config.Contexts), 44 | 0, 45 | } 46 | } 47 | 48 | func getKubeconfigPath() string { 49 | defer fmt.Println() 50 | 51 | if kcfgp := os.Getenv("KUBECTL_PLUGINS_LOCAL_FLAG_KUBECONFIG"); kcfgp != "" { 52 | fmt.Printf("[kubeconfig] Using path '%s'\n", kcfgp) 53 | return kcfgp 54 | } 55 | 56 | fmt.Println("[kubeconfig] Using default path '$HOME/.kube/config'") 57 | home := os.Getenv("HOME") 58 | return fmt.Sprintf("%s/.kube/config", home) 59 | } 60 | 61 | func (m *Manager) Run() { 62 | 63 | for id, context := range m.Original.Contexts { 64 | go m.ValidateAndAddToWorkqueue(id, context) 65 | } 66 | 67 | m.runWorkqueue() 68 | m.RemoveUnusedUsers() 69 | m.Finish() 70 | } 71 | 72 | func (m *Manager) GetKubeconfigPath() string { 73 | return m.path 74 | } 75 | 76 | func (m *Manager) getContextsUser(context *clientcmdapi.Context) *clientcmdapi.AuthInfo { 77 | return m.Original.AuthInfos[context.AuthInfo] 78 | } 79 | 80 | func (m *Manager) getContextsCluster(context *clientcmdapi.Context) *clientcmdapi.Cluster { 81 | return m.Original.Clusters[context.Cluster] 82 | } 83 | 84 | func (m *Manager) removeCluster(cluster string) { 85 | delete(m.New.Clusters, cluster) 86 | } 87 | 88 | func (m *Manager) removeUser(user string) { 89 | delete(m.New.AuthInfos, user) 90 | } 91 | 92 | func (m *Manager) removeContext(context string) { 93 | delete(m.New.Contexts, context) 94 | 95 | } 96 | 97 | func (m *Manager) userIsInUse(user string) bool { 98 | count := 0 99 | 100 | for _, context := range m.New.Contexts { 101 | if context.AuthInfo != user { 102 | continue 103 | } 104 | 105 | count = count + 1 106 | } 107 | 108 | return count > 0 109 | } 110 | 111 | func (m *Manager) RemoveContext(id string, context *clientcmdapi.Context) { 112 | if m.prompter.RemoveContext(id) { 113 | m.removeCluster(context.Cluster) 114 | m.removeContext(id) 115 | } 116 | } 117 | 118 | func (m *Manager) RemoveUnusedUsers() { 119 | for user, _ := range m.New.AuthInfos { 120 | if !m.userIsInUse(user) && m.prompter.RemoveUser(user) { 121 | m.removeUser(user) 122 | } 123 | } 124 | } 125 | 126 | func (m *Manager) Finish() { 127 | config, _ := clientcmd.Write(*m.New) 128 | fmt.Println("----------- NEW KUBECONFIG --------------") 129 | fmt.Print(string(config)) 130 | fmt.Println("-----------------------------------------") 131 | 132 | path := m.GetKubeconfigPath() 133 | if !m.prompter.WriteConfig() { 134 | if !m.prompter.WriteConfigToPath() { 135 | return 136 | } 137 | 138 | path = m.prompter.GetPath() 139 | } 140 | 141 | fmt.Println("Writing file to: ", path) 142 | err := clientcmd.WriteToFile(*m.New, path) 143 | 144 | if err != nil { 145 | fmt.Println(err.Error()) 146 | os.Exit(1) 147 | } 148 | 149 | os.Exit(0) 150 | } 151 | 152 | func (m *Manager) Validate(context *clientcmdapi.Context) (bool, string) { 153 | // make request to server/healz 154 | cluster := m.getContextsCluster(context) 155 | configFromClusterInfo := kubeconfigutil.CreateBasic( 156 | cluster.Server, 157 | context.Cluster, 158 | context.AuthInfo, 159 | cluster.CertificateAuthorityData, 160 | ) 161 | 162 | configFromClusterInfo.AuthInfos[context.AuthInfo] = m.getContextsUser(context) 163 | client, err := kubeconfigutil.ToClientSet(configFromClusterInfo) 164 | if err != nil { 165 | return false, fmt.Sprintf("error converting to clientset: %v", err) 166 | } 167 | _, err = client.CoreV1().ConfigMaps(metav1.NamespacePublic).Get(bootstrapapi.ConfigMapClusterInfo, metav1.GetOptions{}) 168 | if err != nil { 169 | if apierrors.IsForbidden(err) { 170 | // If the request is unauthorized, the cluster admin has not granted access to the cluster info configmap for unauthenticated users 171 | // In that case, trust the cluster admin and do not refresh the cluster-info credentials 172 | return true, fmt.Sprintf("[discovery] Could not access the %s ConfigMap for refreshing the cluster-info information, but the TLS cert is valid so proceeding...", bootstrapapi.ConfigMapClusterInfo) 173 | } 174 | 175 | return false, fmt.Sprintf("[discovery] Failed to validate the API Server's identity, will try again: [%v]", err) 176 | } 177 | 178 | return true, fmt.Sprintf("[discovery] Valid cluster associated with context") 179 | } 180 | -------------------------------------------------------------------------------- /pkg/config/prompt.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | "strings" 8 | ) 9 | 10 | type prompter struct { 11 | reader *bufio.Reader 12 | } 13 | 14 | func NewPrompter() *prompter { 15 | return &prompter{ 16 | bufio.NewReader(os.Stdin), 17 | } 18 | } 19 | 20 | func (p *prompter) getValidYNInput(s string) bool { 21 | text := strings.ToLower(p.getInput(s)) 22 | 23 | if text != "n" && text != "y" { 24 | return p.getValidYNInput(s) 25 | } 26 | 27 | return text == "y" 28 | } 29 | 30 | func (p *prompter) getInput(s string) string { 31 | fmt.Printf(s) 32 | text, _ := p.reader.ReadString('\n') 33 | return strings.Trim(text, " \n") 34 | } 35 | 36 | func (p *prompter) RemoveContext(id string) bool { 37 | return p.getValidYNInput(fmt.Sprintf("Remove '%s' from context (Y/n)? ", id)) 38 | } 39 | 40 | func (p *prompter) RemoveUser(id string) bool { 41 | return p.getValidYNInput(fmt.Sprintf("Remove unused user '%s' from config (Y/n)? ", id)) 42 | } 43 | 44 | func (p *prompter) WriteConfig() bool { 45 | return p.getValidYNInput(fmt.Sprintf("Overwrite kubeconfig (Y/n)? ")) 46 | } 47 | 48 | func (p *prompter) WriteConfigToPath() bool { 49 | return p.getValidYNInput(fmt.Sprintf("Write kubeconfig to a different path (Y/n)? ")) 50 | } 51 | 52 | func (p *prompter) GetPath() string { 53 | return p.getInput(fmt.Sprintf("Path? ")) 54 | } 55 | -------------------------------------------------------------------------------- /pkg/config/workqueue.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | 7 | "github.com/briandowns/spinner" 8 | 9 | clientcmdapi "k8s.io/client-go/tools/clientcmd/api" 10 | ) 11 | 12 | var s *spinner.Spinner 13 | 14 | func init() { 15 | s = spinner.New(spinner.CharSets[9], 100*time.Millisecond) 16 | } 17 | 18 | type ContextResult struct { 19 | ID string 20 | Context *clientcmdapi.Context 21 | Message string 22 | Valid bool 23 | } 24 | 25 | func (m *Manager) ValidateAndAddToWorkqueue(id string, context *clientcmdapi.Context) { 26 | valid, message := m.Validate(context) 27 | m.workqueue <- ContextResult{id, context, message, valid} 28 | m.contextedValidated++ 29 | 30 | if m.contextedValidated == m.totalContexts { 31 | close(m.workqueue) 32 | } 33 | } 34 | 35 | func (m *Manager) runWorkqueue() { 36 | for m.processNextWorkItem() { 37 | } 38 | 39 | return 40 | } 41 | 42 | func (m *Manager) processNextWorkItem() bool { 43 | s.Start() 44 | for n := range m.workqueue { 45 | s.Stop() 46 | fmt.Printf("\nTesting context's '%s' cluster...\n", n.ID) 47 | fmt.Println(n.Message) 48 | 49 | if !n.Valid { 50 | m.RemoveContext(n.ID, n.Context) 51 | } 52 | 53 | s.Start() 54 | } 55 | s.Stop() 56 | 57 | return false 58 | } 59 | -------------------------------------------------------------------------------- /plugin.yaml: -------------------------------------------------------------------------------- 1 | name: "kubeconfig-cleanup" 2 | shortDesc: "clean up dead contexts" 3 | longDesc: "kubeconfig-cleanup will goes through kubeconfig file and helps clean up dead contexts, clusters, and users" 4 | command: "./cleanup" 5 | flags: 6 | - name: "kubeconfig" 7 | desc: "Path to the kubeconfig file" 8 | --------------------------------------------------------------------------------