Skip to content

Commit

Permalink
feat: add --context-name test flag (#684)
Browse files Browse the repository at this point in the history
* feat: add --context-name test flag
  • Loading branch information
sunny0826 authored Apr 23, 2023
1 parent b75290c commit a4c571f
Show file tree
Hide file tree
Showing 38 changed files with 137 additions and 22 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/e2e-test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ jobs:
echo "********************************************************************************"
echo "Running kubecm add..."
echo "********************************************************************************"
bin/kubecm add -f 2nd-kind -c
bin/kubecm add -f 3rd-kind -c
bin/kubecm add -cf 2nd-kind
bin/kubecm add -cf 3rd-kind --context-name 3rd
echo "********************************************************************************"
echo "Running kubecm merge multiple kubeconfig..."
echo "********************************************************************************"
Expand All @@ -89,7 +89,7 @@ jobs:
echo "********************************************************************************"
echo "Running kubecm switch..."
echo "********************************************************************************"
bin/kubecm s kind-3rd-kind
bin/kubecm s 3rd
echo "********************************************************************************"
echo "Running kubecm delete..."
echo "********************************************************************************"
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@ mergeDir
config.yaml
kubecm.config
coverage.txt
example.yaml

merge/
merge/
31 changes: 24 additions & 7 deletions cmd/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,15 @@ func (ac *AddCommand) Init() {
Example: addExample(),
}
ac.command.Flags().StringP("file", "f", "", "Path to merge kubeconfig files")
ac.command.Flags().String("context-name", "", "override context name when add kubeconfig context")
ac.command.PersistentFlags().BoolP("cover", "c", false, "Overwrite local kubeconfig files")
_ = ac.command.MarkFlagRequired("file")
}

func (ac *AddCommand) runAdd(cmd *cobra.Command, args []string) error {
file, _ := ac.command.Flags().GetString("file")
cover, _ := ac.command.Flags().GetBool("cover")
contextName, _ := ac.command.Flags().GetString("context-name")

var newConfig *clientcmdapi.Config
var err error
Expand All @@ -69,15 +71,15 @@ func (ac *AddCommand) runAdd(cmd *cobra.Command, args []string) error {
}
}

err = AddToLocal(newConfig, file, cover)
err = AddToLocal(newConfig, file, contextName, cover)
if err != nil {
return err
}
return nil
}

// AddToLocal add kubeConfig to local
func AddToLocal(newConfig *clientcmdapi.Config, path string, cover bool) error {
func AddToLocal(newConfig *clientcmdapi.Config, path, newName string, cover bool) error {
oldConfig, err := clientcmd.LoadFromFile(cfgFile)
if err != nil {
return err
Expand All @@ -87,7 +89,7 @@ func AddToLocal(newConfig *clientcmdapi.Config, path string, cover bool) error {
fileName: getFileName(path),
}
// merge context loop
outConfig, err := kco.handleContexts(oldConfig)
outConfig, err := kco.handleContexts(oldConfig, newName)
if err != nil {
return err
}
Expand All @@ -109,15 +111,23 @@ func AddToLocal(newConfig *clientcmdapi.Config, path string, cover bool) error {
return nil
}

func (kc *KubeConfigOption) handleContexts(oldConfig *clientcmdapi.Config) (*clientcmdapi.Config, error) {
func (kc *KubeConfigOption) handleContexts(oldConfig *clientcmdapi.Config, contextName string) (*clientcmdapi.Config, error) {
newConfig := clientcmdapi.NewConfig()
var index int
var newName string
for name, ctx := range kc.config.Contexts {
var newName string
if len(kc.config.Contexts) > 1 {
newName = fmt.Sprintf("%s-%s", kc.fileName, HashSufString(name))
} else {
if contextName == "" {
newName = fmt.Sprintf("%s-%s", kc.fileName, HashSufString(name))
} else {
newName = fmt.Sprintf("%s-%d", contextName, index)
}
} else if contextName == "" {
newName = name
} else {
newName = contextName
}

if checkContextName(newName, oldConfig) {
nameConfirm := BoolUI(fmt.Sprintf("「%s」 Name already exists, do you want to rename it. (If you select `False`, this context will not be merged)", newName))
if nameConfirm == "True" {
Expand All @@ -132,6 +142,7 @@ func (kc *KubeConfigOption) handleContexts(oldConfig *clientcmdapi.Config) (*cli
itemConfig := kc.handleContext(oldConfig, newName, ctx)
newConfig = appendConfig(newConfig, itemConfig)
fmt.Printf("Add Context: %s \n", newName)
index++
}
outConfig := appendConfig(oldConfig, newConfig)
return outConfig, nil
Expand Down Expand Up @@ -195,8 +206,14 @@ func (kc *KubeConfigOption) handleContext(oldConfig *clientcmdapi.Config,

func addExample() string {
return `
Note: If -c is set and more than one context is added to the kubeconfig file, the following will occur:
- If --context-name is set, the context will be generated as <context-name-0>, <context-name-1> ...
- If --context-name is not set, it will be generated as <file-name-{hash}> where {hash} is the MD5 hash of the file name.
# Merge test.yaml with $HOME/.kube/config
kubecm add -f test.yaml
# Merge test.yaml with $HOME/.kube/config and rename context name
kubecm add -cf test.yaml --context-name test
# Add kubeconfig from stdin
cat /etc/kubernetes/admin.conf | kubecm add -f -
`
Expand Down
53 changes: 51 additions & 2 deletions cmd/add_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,51 @@ var (
"test-2h6782585t": {AuthInfo: "not-exist", Cluster: "not-exist", Namespace: "not-exist-ns"},
},
}
singleTestConfig = clientcmdapi.Config{
AuthInfos: map[string]*clientcmdapi.AuthInfo{
"single-user": {Token: "single-token"},
},
Clusters: map[string]*clientcmdapi.Cluster{
"single-cluster": {Server: "http://single:8080"},
},
Contexts: map[string]*clientcmdapi.Context{
"single-context": {AuthInfo: "single-user", Cluster: "single-cluster", Namespace: "single-ns"},
},
}
mergeSingleTestConfig = clientcmdapi.Config{
AuthInfos: map[string]*clientcmdapi.AuthInfo{
"black-user": {Token: "black-token"},
"red-user": {Token: "red-token"},
"single-user": {Token: "single-token"},
},
Clusters: map[string]*clientcmdapi.Cluster{
"pig-cluster": {Server: "http://pig.org:8080"},
"cow-cluster": {Server: "http://cow.org:8080"},
"single-cluster": {Server: "http://single:8080"},
},
Contexts: map[string]*clientcmdapi.Context{
"root": {AuthInfo: "black-user", Cluster: "pig-cluster", Namespace: "saw-ns"},
"federal": {AuthInfo: "red-user", Cluster: "cow-cluster", Namespace: "hammer-ns"},
"single-context": {AuthInfo: "single-user", Cluster: "single-cluster", Namespace: "single-ns"},
},
}
renameSingleTestConfig = clientcmdapi.Config{
AuthInfos: map[string]*clientcmdapi.AuthInfo{
"black-user": {Token: "black-token"},
"red-user": {Token: "red-token"},
"single-user": {Token: "single-token"},
},
Clusters: map[string]*clientcmdapi.Cluster{
"pig-cluster": {Server: "http://pig.org:8080"},
"cow-cluster": {Server: "http://cow.org:8080"},
"single-cluster": {Server: "http://single:8080"},
},
Contexts: map[string]*clientcmdapi.Context{
"root": {AuthInfo: "black-user", Cluster: "pig-cluster", Namespace: "saw-ns"},
"federal": {AuthInfo: "red-user", Cluster: "cow-cluster", Namespace: "hammer-ns"},
"rename": {AuthInfo: "single-user", Cluster: "single-cluster", Namespace: "single-ns"},
},
}
)

func Test_checkContextName(t *testing.T) {
Expand Down Expand Up @@ -137,12 +182,14 @@ func TestKubeConfig_handleContext(t *testing.T) {

func TestKubeConfig_handleContexts(t *testing.T) {
newConfig := addTestConfig.DeepCopy()
singleConfig := singleTestConfig.DeepCopy()
type fields struct {
config *clientcmdapi.Config
fileName string
}
type args struct {
oldConfig *clientcmdapi.Config
newName string
}
tests := []struct {
name string
Expand All @@ -152,15 +199,17 @@ func TestKubeConfig_handleContexts(t *testing.T) {
wantErr bool
}{
// TODO: Add test cases.
{"test", fields{config: newConfig, fileName: "test"}, args{&oldTestConfig}, &mergedConfig, false},
{"not have new context name", fields{config: newConfig, fileName: "test"}, args{&oldTestConfig, ""}, &mergedConfig, false},
{"single context name", fields{config: singleConfig, fileName: "test"}, args{&oldTestConfig, ""}, &mergeSingleTestConfig, false},
{"single context name - new", fields{config: singleConfig, fileName: "test"}, args{&oldTestConfig, "rename"}, &renameSingleTestConfig, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
kc := &KubeConfigOption{
config: tt.fields.config,
fileName: tt.fields.fileName,
}
got, err := kc.handleContexts(tt.args.oldConfig)
got, err := kc.handleContexts(tt.args.oldConfig, tt.args.newName)
if (err != nil) != tt.wantErr {
t.Errorf("handleContexts() error = %v, wantErr %v", err, tt.wantErr)
return
Expand Down
12 changes: 6 additions & 6 deletions cmd/cloud_add.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func (ca *CloudAddCommand) runCloudAdd(cmd *cobra.Command, args []string) error
if err != nil {
return err
}
err = AddToLocal(newConfig, clusters[clusterNum].Name, cover)
err = AddToLocal(newConfig, clusters[clusterNum].Name, "", cover)
if err != nil {
return err
}
Expand All @@ -83,7 +83,7 @@ func (ca *CloudAddCommand) runCloudAdd(cmd *cobra.Command, args []string) error
if err != nil {
return err
}
err = AddToLocal(newConfig, fmt.Sprintf("alicloud-%s", clusterID), cover)
err = AddToLocal(newConfig, fmt.Sprintf("alicloud-%s", clusterID), "", cover)
if err != nil {
return err
}
Expand Down Expand Up @@ -123,7 +123,7 @@ func (ca *CloudAddCommand) runCloudAdd(cmd *cobra.Command, args []string) error
if err != nil {
return err
}
err = AddToLocal(newConfig, clusters[clusterNum].Name, cover)
err = AddToLocal(newConfig, clusters[clusterNum].Name, "", cover)
if err != nil {
return err
}
Expand All @@ -136,7 +136,7 @@ func (ca *CloudAddCommand) runCloudAdd(cmd *cobra.Command, args []string) error
if err != nil {
return err
}
err = AddToLocal(newConfig, fmt.Sprintf("tencent-%s", clusterID), cover)
err = AddToLocal(newConfig, fmt.Sprintf("tencent-%s", clusterID), "", cover)
if err != nil {
return err
}
Expand Down Expand Up @@ -165,7 +165,7 @@ func (ca *CloudAddCommand) runCloudAdd(cmd *cobra.Command, args []string) error
if err != nil {
return err
}
err = AddToLocal(newConfig, clusters[clusterNum].Name, cover)
err = AddToLocal(newConfig, clusters[clusterNum].Name, "", cover)
if err != nil {
return err
}
Expand All @@ -178,7 +178,7 @@ func (ca *CloudAddCommand) runCloudAdd(cmd *cobra.Command, args []string) error
if err != nil {
return err
}
err = AddToLocal(newConfig, fmt.Sprintf("rancher-%s", clusterID), cover)
err = AddToLocal(newConfig, fmt.Sprintf("rancher-%s", clusterID), "", cover)
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/merge.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func (mc MergeCommand) runMerge(command *cobra.Command, args []string) error {
config: loadConfig,
fileName: getFileName(yaml),
}
outConfigs, err = kco.handleContexts(outConfigs)
outConfigs, err = kco.handleContexts(outConfigs, "")
if err != nil {
return err
}
Expand Down
1 change: 1 addition & 0 deletions docs/en-us/cli/kubecm.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ KubeConfig Manager.
```
--config string path of kubeconfig (default "/Users/guoxudong/.kube/config")
-h, --help help for kubecm
-m, --mac-notify enable to display Mac notification banner
--ui-size int number of list items to show in menu at once (default 4)
```

Expand Down
9 changes: 9 additions & 0 deletions docs/en-us/cli/kubecm_add.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,18 @@ Add KubeConfig to $HOME/.kube/config
kubecm add [flags]
```

>Note: If `-c` is set and **more than one** context is added to the kubeconfig file, the following will occur:
>- If `--context-name` is set, the context will be generated as `<context-name-0>`, `<context-name-1>` ...
>- If `--context-name` is not set, it will be generated as `<file-name-{hash}>` where `{hash}` is the MD5 hash of the file name.
### Examples

```
# Merge test.yaml with $HOME/.kube/config
kubecm add -f test.yaml
# Merge test.yaml with $HOME/.kube/config and rename context name
kubecm add -cf test.yaml --context-name test
# Add kubeconfig from stdin
cat /etc/kubernetes/admin.conf | kubecm add -f -
Expand All @@ -24,15 +30,18 @@ cat /etc/kubernetes/admin.conf | kubecm add -f -
### Options

```
--context-name string override context name when add kubeconfig context
-c, --cover Overwrite local kubeconfig files
-f, --file string Path to merge kubeconfig files
-h, --help help for add
```

### Options inherited from parent commands

```
--config string path of kubeconfig (default "/Users/guoxudong/.kube/config")
-m, --mac-notify enable to display Mac notification banner
--ui-size int number of list items to show in menu at once (default 4)
```

Expand Down
1 change: 1 addition & 0 deletions docs/en-us/cli/kubecm_alias.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ $ kubecm alias -o bash

```
--config string path of kubeconfig (default "/Users/guoxudong/.kube/config")
-m, --mac-notify enable to display Mac notification banner
--ui-size int number of list items to show in menu at once (default 4)
```

Expand Down
1 change: 1 addition & 0 deletions docs/en-us/cli/kubecm_clear.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ kubecm clear config.yaml test.yaml

```
--config string path of kubeconfig (default "/Users/guoxudong/.kube/config")
-m, --mac-notify enable to display Mac notification banner
--ui-size int number of list items to show in menu at once (default 4)
```

Expand Down
1 change: 1 addition & 0 deletions docs/en-us/cli/kubecm_cloud.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Manage kubeconfig from cloud

```
--config string path of kubeconfig (default "/Users/guoxudong/.kube/config")
-m, --mac-notify enable to display Mac notification banner
--ui-size int number of list items to show in menu at once (default 4)
```

Expand Down
1 change: 1 addition & 0 deletions docs/en-us/cli/kubecm_cloud_add.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ kubecm cloud add --provider alibabacloud --cluster_id=xxxxxx
--config string path of kubeconfig (default "/Users/guoxudong/.kube/config")
--provider string public cloud
--region_id string cloud region id
-m, --mac-notify enable to display Mac notification banner
--ui-size int number of list items to show in menu at once (default 4)
```

Expand Down
1 change: 1 addition & 0 deletions docs/en-us/cli/kubecm_cloud_list.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ kubecm cloud list --provider alibabacloud --cluster_id=xxxxxx
--config string path of kubeconfig (default "/Users/guoxudong/.kube/config")
--provider string public cloud
--region_id string cloud region id
-m, --mac-notify enable to display Mac notification banner
--ui-size int number of list items to show in menu at once (default 4)
```

Expand Down
1 change: 1 addition & 0 deletions docs/en-us/cli/kubecm_completion.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ kubecm completion [bash|zsh|fish|powershell] [flags]

```
--config string path of kubeconfig (default "/Users/guoxudong/.kube/config")
-m, --mac-notify enable to display Mac notification banner
--ui-size int number of list items to show in menu at once (default 4)
```

Expand Down
1 change: 1 addition & 0 deletions docs/en-us/cli/kubecm_create.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ kubecm create

```
--config string path of kubeconfig (default "/Users/guoxudong/.kube/config")
-m, --mac-notify enable to display Mac notification banner
--ui-size int number of list items to show in menu at once (default 4)
```

Expand Down
1 change: 1 addition & 0 deletions docs/en-us/cli/kubecm_delete.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ kubecm delete my-context1 my-context2

```
--config string path of kubeconfig (default "/Users/guoxudong/.kube/config")
-m, --mac-notify enable to display Mac notification banner
--ui-size int number of list items to show in menu at once (default 4)
```

Expand Down
1 change: 1 addition & 0 deletions docs/en-us/cli/kubecm_list.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ kubecm ls kind k3s

```
--config string path of kubeconfig (default "/Users/guoxudong/.kube/config")
-m, --mac-notify enable to display Mac notification banner
--ui-size int number of list items to show in menu at once (default 4)
```

Expand Down
1 change: 1 addition & 0 deletions docs/en-us/cli/kubecm_merge.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ kubecm merge -f dir --config kubecm.config

```
--config string path of kubeconfig (default "/Users/guoxudong/.kube/config")
-m, --mac-notify enable to display Mac notification banner
--ui-size int number of list items to show in menu at once (default 4)
```

Expand Down
Loading

0 comments on commit a4c571f

Please sign in to comment.