Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
DalianisDim committed Jun 4, 2023
0 parents commit bc4fbe2
Show file tree
Hide file tree
Showing 9 changed files with 1,035 additions and 0 deletions.
23 changes: 23 additions & 0 deletions .cobra.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
author: Dimitris Dalianis <[email protected]>
year: 2023
useViper: true
license:
header: This file is part of CLI application keyvalDetector
text: |
{{ .copyright }}
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
59 changes: 59 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
name: Release

on:
push:
tags:
- '*'

jobs:
publish:
name: Publish for ${{ matrix.asset_name}}
runs-on: ${{ matrix.os }}
strategy:
matrix:
include:
- os: ubuntu-latest
artifact_name: keyvalDetector
asset_name: keyvalDetector-linux-amd64
build_params: "GOOS=linux GOARCH=amd64"
# - os: windows-latest
# artifact_name: keyvalDetector.exe
# asset_name: keyvalDetector-windows-amd64
# build_params: "GOOS=windows GOARCH=amd64"
- os: macos-latest
artifact_name: keyvalDetector
asset_name: keyvalDetector-macos-amd64
build_params: "GOOS=darwin GOARCH=amd64"
- os: macos-latest
artifact_name: keyvalDetector
asset_name: keyvalDetector-macos-arm64
build_params: "GOOS=darwin GOARCH=arm64"

steps:
- uses: actions/checkout@v3

- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: '1.20'
cache-dependency-path: go.sum

- name: Install dependencies
run: |
go get .
- name: Build
run: |
${{ matrix.build_params }} go build --ldflags="-X 'keyvalDetector/cmd.buildTimeVersion=${{ github.ref_name }}'"
- name: Test with the Go CLI
run: go test

- uses: svenstaro/upload-release-action@v2
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
file: ${{ matrix.artifact_name }}
asset_name: ${{ matrix.asset_name }}
tag: ${{ github.ref }}
overwrite: true
body: "Version ${{ github.ref_name }}"
17 changes: 17 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
Copyright © 2023 Dimitris Dalianis <[email protected]>

This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@


# kubevalDetector

**keyvalDetector** will scan your Kubernetes cluster for ConfigMaps and Secrets that are not used by Pods.

It uses the current Kubernetes context by default, therefore in its simplest form it can be ran without any flag:

```
kubevalDetector
```

## Usage

```
keyvalDetector [flags]
Flags:
-c, --config string Config file (default is $HOME/.keyvalDetector.yaml)
-h, --help help for keyvalDetector
-v, --version Print the version and exit.
```
20 changes: 20 additions & 0 deletions cmd/helpers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
Copyright © 2023 Dimitris Dalianis <[email protected]>
This file is part of CLI application keyvalDetector
*/
package cmd

import "fmt"

func printSlice(s []string) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}

func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
236 changes: 236 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
/*
Copyright © 2023 Dimitris Dalianis <[email protected]>
This file is part of CLI application keyvalDetector
*/
package cmd

import (
"context"
"fmt"
"os"

"github.com/olekukonko/tablewriter"

"github.com/spf13/cobra"
"github.com/spf13/viper"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
)

var cfgFile string
var version bool
var buildTimeVersion string
var defaultKubeConfigPath = "/.kube/config"

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "keyvalDetector",
Version: buildTimeVersion,
Short: "Scan your k8s cluster for unused ConfigMaps and Secrets",
Long: `keyvalDetector will scan your Kubernetes cluster for
ConfigMaps and Secrets that are not used by Pods.`,
// Uncomment the following line if your bare application
// has an action associated with it:
Run: func(cmd *cobra.Command, args []string) {
keyvalDetector()
},
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}

func init() {
cobra.OnInitialize(initConfig)

// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.

rootCmd.Flags().StringVarP(&cfgFile, "config", "c", "", "Config file (default is $HOME/.keyvalDetector.yaml)")
rootCmd.Flags().BoolVarP(&version, "version", "v", version, "Print the version and exit.")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := os.UserHomeDir()
cobra.CheckErr(err)

// Search config in home directory with name ".keyvalDetector" (without extension).
viper.AddConfigPath(home)
viper.SetConfigType("yaml")
viper.SetConfigName(".keyvalDetector")
}

viper.AutomaticEnv() // read in environment variables that match

// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
}
}

func keyvalDetector() error {

var configMapsOut [][]string
var secretsOut [][]string

// uses the current context in kubeconfig
// path-to-kubeconfig -- for example, /root/.kube/config
config, _ := clientcmd.BuildConfigFromFlags("", homedir.HomeDir()+defaultKubeConfigPath)

// creates the clientset
clientset, _ := kubernetes.NewForConfig(config)

// List all the namespaces in the cluster.
namespaces, err := clientset.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
if err != nil {
panic(err)
}

// Foreach namespace, get configmaps, secrets and pods.
// Then check pod's mounts

// Foreach namespace
for _, namespace := range namespaces.Items {
// Slice to store used ConfigMap names
namespaceUsedConfigMaps := []string{}

// Slice to store used Secrets names
namespaceUsedSecrets := []string{}

// List all pods in current namespace
pods, err := clientset.CoreV1().Pods(namespace.GetName()).List(context.Background(), metav1.ListOptions{})
if err != nil {
panic(err)
}

// List all configmaps in current namespace
configmaps, err := clientset.CoreV1().ConfigMaps(namespace.GetName()).List(context.Background(), metav1.ListOptions{})
if err != nil {
panic(err)
}

// List all secrets in current namespace
secrets, err := clientset.CoreV1().Secrets(namespace.GetName()).List(context.Background(), metav1.ListOptions{})
if err != nil {
panic(err)
}

// Iterate over the pods
// Check each pod's Volumes and store the configmaps and secrets mounted names on a separate slice
// Compare lists of configmaps/secrets with mounted ones
for _, pod := range pods.Items {
// Foreach pod's volume
for _, volume := range pod.Spec.Volumes {
if volume.ConfigMap != nil {
namespaceUsedConfigMaps = append(namespaceUsedConfigMaps, volume.ConfigMap.Name)
}
if volume.Secret != nil {
namespaceUsedSecrets = append(namespaceUsedSecrets, volume.Secret.SecretName)
}
}

// Foreach container in pod
for _, container := range pod.Spec.Containers {
for _, envFrom := range container.EnvFrom {
if envFrom.ConfigMapRef != nil {
namespaceUsedConfigMaps = append(namespaceUsedConfigMaps, envFrom.ConfigMapRef.Name)
}
if envFrom.SecretRef != nil {
namespaceUsedSecrets = append(namespaceUsedSecrets, envFrom.SecretRef.Name)
}
}
for _, env := range container.Env {
if env.ValueFrom != nil {
if env.ValueFrom.ConfigMapKeyRef != nil {
namespaceUsedConfigMaps = append(namespaceUsedConfigMaps, env.ValueFrom.ConfigMapKeyRef.Name)
}
if env.ValueFrom.SecretKeyRef != nil {
namespaceUsedSecrets = append(namespaceUsedSecrets, env.ValueFrom.SecretKeyRef.Name)
}
}
}
}
} // END - Foreach pod

// Check if configmaps/secrets of this namespace
// are in namespaceUsedConfigMaps/namespaceUsedSecrets
for _, configmap := range configmaps.Items {
if !contains(namespaceUsedConfigMaps, configmap.GetName()) {
if !isSystemConfigMap(configmap.GetName()) {
configMapsOut = append(configMapsOut, []string{configmap.GetName(), namespace.GetName()})
}
}
}

for _, secret := range secrets.Items {
if !isSystemSecret(secret.GetName()) {
if !contains(namespaceUsedSecrets, secret.GetName()) {
secretsOut = append(secretsOut, []string{secret.GetName(), namespace.GetName()})
}
}
}

} // END - Foreach namespace

// Construct ConfigMaps table
configMapsTable := tablewriter.NewWriter(os.Stdout)
configMapsTable.SetHeader([]string{"Name", "Namespace"})

for _, v := range configMapsOut {
configMapsTable.Append(v)
}
fmt.Print("Unused ConfigMaps: \n")
configMapsTable.Render() // Send output

// Construct Secrets table
secretsTable := tablewriter.NewWriter(os.Stdout)
secretsTable.SetHeader([]string{"Name", "Namespace"})

for _, v := range secretsOut {
secretsTable.Append(v)
}
fmt.Print("\n\nUnused Secrets: \n")
secretsTable.Render() // Send output

return nil
}

// func test(clientset kubernetes.Clientset) {

// }

func isSystemConfigMap(configmap string) bool {
defaultConfigMaps := []string{"kube-root-ca.crt", "cluster-info", "kubelet-config", "kubeadm-config"}

for _, value := range defaultConfigMaps {
if configmap == value {
return true
}
}
return false
}

func isSystemSecret(secret string) bool {
defaultSecrets := []string{"foobar"}

for _, value := range defaultSecrets {
if secret == value {
return true
}
}
return false
}
Loading

0 comments on commit bc4fbe2

Please sign in to comment.