Skip to content
This repository has been archived by the owner on Apr 12, 2024. It is now read-only.

Commit

Permalink
Fixed and improved list command
Browse files Browse the repository at this point in the history
  • Loading branch information
Matteo Baiguini committed Feb 7, 2022
1 parent e3b50f3 commit ebe035c
Show file tree
Hide file tree
Showing 8 changed files with 121 additions and 65 deletions.
30 changes: 17 additions & 13 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@

# VARIABLES
KONF_LOG_ENCODING ?= console
KONF_LOG_LEVEL ?= info
KONF_PREFIX := KONF_LOG_LEVEL=$(KONF_LOG_LEVEL)
KONF_PREFIX := KONF_LOG_ENCODING=$(KONF_LOG_ENCODING) KONF_LOG_LEVEL=$(KONF_LOG_LEVEL)
## global
export GO111MODULE = on


# CONFIG
Expand All @@ -11,20 +14,19 @@ KONF_PREFIX := KONF_LOG_LEVEL=$(KONF_LOG_LEVEL)

# ACTIONS

## commands

run : ## Debug running directly from source code
go run main.go
## code

build : ## Build
@export GO111MODULE=on && \
go build -o konf-sh .

run-bin : build ## Run
konf-sh $(ARGS)
clean : ## Clean
-@rm -rf konf-sh

clean-bin : ## Clean binary
@rm -rf konf-sh >/dev/null 2>&1
#TODO
#test : ## Test
# go test -coverprofile=coverage.out -count=5 -race ./...

## release

release : ## Create a new git tag and push it to remote to trigger the release GitHub action
ifdef NEW_VERSION
Expand All @@ -37,7 +39,7 @@ endif
simulate-release : ## Simulate a release with goreleaser
goreleaser release --rm-dist --snapshot --skip-publish

## features samples
## commands

split : build ## Split a sample Kubernetes configuration file
$(KONF_PREFIX) konf-sh split --kube-config ./examples/config --single-konfigs ./examples/konfigs
Expand Down Expand Up @@ -78,8 +80,10 @@ reset-global : build ## Reset global Kubernetes configuration

## helpers

reset-config-sample : ## Reset Kubernetes configuration sample to original
cp -f ./examples/config_origin ./examples/config
restore-origin-example : ## Restore original example
@rm -rf ./examples/konfigs/context_*
@cp -f ./examples/config_origin ./examples/config
@cp -f ./examples/context_invalid ./examples/konfigs/context_invalid

help : ## Help
@echo ""
Expand Down
57 changes: 53 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
- [3. Install autocompletion](#3-install-autocompletion)
- [4. Advised customisations](#4-advised-customisations)
- [Usage](#usage)
- [Commands](#commands)
- [Some tech details](#some-tech-details)
- [Flags](#flags)
- [Environment variables](#environment-variables)
Expand Down Expand Up @@ -126,17 +127,65 @@ alias kns="konf ns"

## Usage

### 1. Split k8s config

First we have to split your Kubernetes config into multiple single Kubernetes konfigs

```sh
konf split
```

If we don't do this, no other command will have any effect.

### 2. List all available k8s konfigs

Let's list all available k8s konfigs to select the right k8s ctx we want to set

```sh
konf list
```

### 3. Set a global k8s ctx

We set our k8s ctx as global

```sh
konf set global <context>
```

### 4. Set a local k8s ctx

We open another terminal because we need access to different k8s ctx, then we execute

```sh
konf set local <context>
```

This will point our kubectl to the selected k8s ctx, but ONLY IN THE CURRENT SHELL! Amazing don't you think?

### 5. View our settings

Still from the second terminal window, we want to review our current settings

```sh
konf view
```

---

## Commands

### Split

`konf split` separates the Kubernetes configuration (by default `~/.kube/config`) into single Kubernetes konfigurations files (by default in `~/.kube/konfigs`).
`konf split` separates the Kubernetes configuration (by default `~/.kube/config`) into single Kubernetes konfigurations files (by default in `~/.kube/konfigs`), one for each context.

### List

`konf list` lists all single Kubernetes konfigurations files separated by `konf split` (by default in `~/.kube/konfigs`).

### Set

`konf set local <context>` sets the local (current shell) Kubernetes context (setting `KUBECONFIG` environment variable) to the specified one (by default `~/.kube/konfigs`).
konf set local <context> sets the local (current shell) Kubernetes context (setting `KUBECONFIG` environment variable) to the specified one (by default `~/.kube/konfigs`).

`konf set global <context>` sets the global Kubernetes context (by default `currentContext` in `~/.kube/config`) to the specified one (by default `~/.kube/konfigs`).

Expand Down Expand Up @@ -183,7 +232,7 @@ alias kns="konf ns"
| Flag | Command list | Available values | Default | Corresponding env-var | Description |
|:-----------------|:-------------------------------------|:-----------------|:---------------------|:------------------------------|:--------------------------------------------------------|
| --kube-config | split, view, view global, set global | - | $HOME/.kube/config | KONF_KUBE_CONFIG_PATH | Specify a custom Kubernetes configuration file path |
| --single-konfigs | split, list, set local, set global | - | $HOME/.kube/konfigs/ | KONF_SINGLE_KUBE_CONFIGS_PATH | Specify the single Kubernetes konfigurations files path |
| --single-konfigs | split, list, set local, set global | - | $HOME/.kube/konfigs/ | KONF_SINGLE_KUBE_KONFIGS_PATH | Specify the single Kubernetes konfigurations files path |

### Environment variables

Expand All @@ -192,7 +241,7 @@ alias kns="konf ns"
| KONF_LOG_ENCODING | (global) | console, json | console | - | Set logger encoding |
| KONF_LOG_LEVEL | (global) | debug, info, warn, error, fatal | info | - | Set logger level |
| KONF_KUBE_CONFIG_PATH | split, view, view global, set global | - | $HOME/.kube/config | --kube-config | Specify a custom Kubernetes configuration file path |
| KONF_SINGLE_KUBE_CONFIGS_PATH | split, list, set local, set global | - | $HOME/.kube/konfigs/ | --single-konfigs | Specify the single Kubernetes konfigurations files path |
| KONF_SINGLE_KUBE_KONFIGS_PATH | split, list, set local, set global | - | $HOME/.kube/konfigs/ | --single-konfigs | Specify the single Kubernetes konfigurations files path |

### Error codes

Expand Down
44 changes: 37 additions & 7 deletions cmd/list/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import (
"fmt"
"os"
"path/filepath"
"strings"

"github.com/bygui86/konf-sh/pkg/commons"
"github.com/bygui86/konf-sh/pkg/kubeconfig"
"github.com/bygui86/konf-sh/pkg/logger"
"github.com/bygui86/konf-sh/pkg/utils"
"github.com/urfave/cli/v2"
Expand All @@ -25,18 +27,46 @@ func list(ctx *cli.Context) error {
logger.SugaredLogger.Warn("⚠️ Single Kubernetes konfigurations files path not found")
logger.SugaredLogger.Warn("ℹ️ Tip: run 'konf split' before 'konf list'")
} else {
logger.SugaredLogger.Infof("📚 List single Kubernetes konfigurations in '%s':", singleConfigsPath)
err := filepath.Walk(singleConfigsPath, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
logger.SugaredLogger.Infof("\t%s", info.Name())
}
return nil
})
validCfg := make([]string, 0)
invalidCfg := make([]string, 0)
err := filepath.Walk(
singleConfigsPath,
func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}

if strings.HasPrefix(info.Name(), ".") {
return nil
}

kCfg := kubeconfig.Load(path)
// INFO: no need to check if kubeConfig is nil, because the inner method called will exit if it does not find the configuration file
if kubeconfig.Validate(kCfg) != nil {
invalidCfg = append(invalidCfg, info.Name())
return nil
}

validCfg = append(validCfg, info.Name())

return nil
},
)
if err != nil {
return cli.Exit(
fmt.Sprintf("❌ Error listing single Kubernetes konfigurations in '%s': %s", singleConfigsPath, err.Error()),
21)
}

logger.SugaredLogger.Infof("📚 Available Kubernetes konfigurations in '%s':", singleConfigsPath)
for _, v := range validCfg {
logger.SugaredLogger.Infof("\t%s", v)
}
logger.Logger.Info("")
logger.SugaredLogger.Infof("❓️ Invalid Kubernetes konfigurations in '%s':", singleConfigsPath)
for _, iv := range invalidCfg {
logger.SugaredLogger.Infof("\t%s", iv)
}
}

logger.Logger.Info("")
Expand Down
4 changes: 2 additions & 2 deletions cmd/split/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func split(ctx *cli.Context) error {
12)
}

logger.SugaredLogger.Infof("✂️ Split Kubernetes configuration from %s", kubeConfigFilePath)
logger.SugaredLogger.Infof("✂️ Split Kubernetes configuration from %s", kubeConfigFilePath)
singleConfigs := kubeconfig.Split(kubeConfig, kubeConfigFilePath)

logger.Logger.Info("💾 Save single Kubernetes konfigurations files")
Expand All @@ -52,7 +52,7 @@ func split(ctx *cli.Context) error {
return valWrErr
}

logger.SugaredLogger.Infof("✅ Completed! Single Kubernetes konfigurations files saved in '%s'", singleConfigsPath)
logger.SugaredLogger.Infof("✅ Completed! Single Kubernetes konfigurations files saved in '%s'", singleConfigsPath)
logger.Logger.Info("")
return nil
}
Expand Down
7 changes: 4 additions & 3 deletions docs/roadmap.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@
- [x] split
- [x] view
- [x] rename binary to "konf-sh"
- [ ] fix "list konfigs"
- [ ] hide .DS_store and other files
- [ ] show only valid kubeconfig
- [x] fix "list konfigs"
- [x] hide .DS_store and other files
- [x] show only valid kubeconfig
- [ ] improve "clean" command
- [x] rename to "delete"
- [ ] remove ctx from both "~/.kube/config" and "~/.kube/konfigs"
Expand All @@ -59,6 +59,7 @@
- [ ] shellwrapper
- [ ] implement command
- [ ] fix "konf set local <context>"
- [ ] refactor logger (replace logger.Logger with zap.L())

### v0.4.0 ✅

Expand Down
27 changes: 0 additions & 27 deletions examples/configs/context_b

This file was deleted.

15 changes: 7 additions & 8 deletions examples/configs/context_a → examples/context_invalid
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,23 @@ clusters:
- cluster:
certificate-authority-data: Y2VydGlmaWNhdGUtYXV0aG9yaXR5LWRhdGFfc2FtcGxl
server: https://127.0.0.1
name: cluster_a
name: cluster_c
contexts:
- context:
cluster: cluster_a
namespace: default
user: john
name: context_a
current-context: context_a
cluster: cluster_c
namespace: monitoring
user: clint
name: context_c
kind: Config
preferences: {}
users:
- name: john
- name: clint
user:
auth-provider:
config:
access-token: access-token_sample
cmd-args: config config-helper --format=json
cmd-path: /Users/mbaiguini/tools/google-cloud-sdk/bin/gcloud
cmd-path: /Users/clint/tools/google-cloud-sdk/bin/gcloud
expiry: "2022-01-01T12:00:00Z"
expiry-key: '{.credential.token_expiry}'
token-key: '{.credential.access_token}'
Expand Down
2 changes: 1 addition & 1 deletion pkg/commons/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const (
// Environment variables
KubeConfigPathEnvVar = "KONF_KUBE_CONFIG_PATH"
KubeConfigPathDefault = ".kube/config"
SingleKonfigsPathEnvVar = "KONF_SINGLE_KUBE_CONFIGS_PATH"
SingleKonfigsPathEnvVar = "KONF_SINGLE_KUBE_KONFIGS_PATH"
SingleKonfigsPathDefault = ".kube/konfigs"
KubeConfigEnvVar = "KUBECONFIG"
KubeConfigEnvVarDefault = ""
Expand Down

0 comments on commit ebe035c

Please sign in to comment.