Skip to content

Commit

Permalink
use default clientcmd loading behavior (#15)
Browse files Browse the repository at this point in the history
* fix #14 respect KUBECONFIG env var

* use default loading rules in clientcmd
* if -kubeconfig flag is set, override default loading (old
  behaviour)
* use non-deprecated discoveryclient and resource list func
* use Homedir() from client-go/util
* cleanup flag declarations
* basic bash test
* mod tidy

* re-add flag parse, fix sh tests

* rename workflow

* fix test, remove extraneous var/comment

* use non-deprecated serializer for output

* update workflow, ignore idea

newline
  • Loading branch information
coopernetes authored Apr 23, 2022
1 parent 7267da4 commit f79eaf9
Show file tree
Hide file tree
Showing 6 changed files with 44 additions and 57 deletions.
7 changes: 2 additions & 5 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
name: Go & K8s build
on:
push:
branches:
- "*"
name: build/test
on: [push]
jobs:
build:
runs-on: ubuntu-latest
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
.vscode
.idea/
dist/
3 changes: 1 addition & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ require (
github.com/google/go-cmp v0.5.7 // indirect
github.com/google/gofuzz v1.2.0 // indirect
github.com/googleapis/gnostic v0.5.5 // indirect
github.com/imdario/mergo v0.3.12 // indirect
github.com/imdario/mergo v0.3.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
Expand All @@ -34,7 +34,6 @@ require (
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
k8s.io/klog/v2 v2.40.1 // indirect
k8s.io/kube-openapi v0.0.0-20220124234850-424119656bbf // indirect
k8s.io/utils v0.0.0-20220127004650-9b3446523e65 // indirect
sigs.k8s.io/json v0.0.0-20211208200746-9f7c6b3444d2 // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.2.1 // indirect
Expand Down
10 changes: 1 addition & 9 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ github.com/evanphx/json-patch v4.12.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQL
github.com/form3tech-oss/jwt-go v3.2.2+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k=
github.com/form3tech-oss/jwt-go v3.2.3+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/getkin/kin-openapi v0.76.0/go.mod h1:660oXbgy5JFMKreazJaQTw7o+X00qeSyhcnluiMv+Xg=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
Expand Down Expand Up @@ -174,9 +173,8 @@ github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/imdario/mergo v0.3.5 h1:JboBksRwiiAJWvIYJVo46AfV+IAIKZpfrSzVKj42R4Q=
github.com/imdario/mergo v0.3.5/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA=
github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU=
github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
Expand Down Expand Up @@ -204,16 +202,13 @@ github.com/munnerz/goautoneg v0.0.0-20120707110453-a547fc61f48d/go.mod h1:+n7T8m
github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
github.com/onsi/ginkgo v1.14.0 h1:2mOpI4JVVPBN+WQRa0WKH2eXR+Ey+uK4n7Zj0aYpIQA=
github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY=
github.com/onsi/gomega v0.0.0-20170829124025-dcabb60a477c/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1 h1:o0+MgICZLuZ7xjH7Vx6zS/zcu93/BEp1VwkIW1mEXCE=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
Expand Down Expand Up @@ -583,7 +578,6 @@ gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
Expand Down Expand Up @@ -616,8 +610,6 @@ k8s.io/klog/v2 v2.30.0/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0=
k8s.io/klog/v2 v2.40.1 h1:P4RRucWk/lFOlDdkAr3mc7iWFkgKrZY9qZMAgek06S4=
k8s.io/klog/v2 v2.40.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0=
k8s.io/kube-openapi v0.0.0-20211115234752-e816edb12b65/go.mod h1:sX9MT8g7NVZM5lVL/j8QyCCJe8YSMW30QvGZWaCIDIk=
k8s.io/kube-openapi v0.0.0-20220124234850-424119656bbf h1:M9XBsiMslw2lb2ZzglC0TOkBPK5NQi0/noUrdnoFwUg=
k8s.io/kube-openapi v0.0.0-20220124234850-424119656bbf/go.mod h1:sX9MT8g7NVZM5lVL/j8QyCCJe8YSMW30QvGZWaCIDIk=
k8s.io/utils v0.0.0-20210802155522-efc7438f0176/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA=
k8s.io/utils v0.0.0-20211116205334-6203023598ed/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA=
k8s.io/utils v0.0.0-20220127004650-9b3446523e65 h1:ONWS0Wgdg5wRiQIAui7L/023aC9+IxrIrydY7l8llsE=
Expand Down
73 changes: 32 additions & 41 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,57 +4,55 @@ import (
"bytes"
"flag"
"fmt"
"log"
"os"
"sort"
"path/filepath"
"strings"
"github.com/elliotchance/orderedmap"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8sJson "k8s.io/apimachinery/pkg/runtime/serializer/json"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/discovery"
"k8s.io/client-go/tools/clientcmd"
"log"
"os"
"sort"
"strings"
)

func main() {

var roleNameArg string
flag.StringVar(&roleNameArg, "name", "foo-clusterrole", "Override the name of the ClusterRole resource that is generated")

var enableVerboseLogging bool
flag.BoolVar(&enableVerboseLogging, "v", false, "Enable verbose logging")
roleNameArg := flag.String("name", "foo-clusterrole", "Override the name of the ClusterRole "+
"resource that is generated")
enableVerboseLogging := flag.Bool("v", false, "Enable verbose logging")
kubeconfigFlag := flag.String("kubeconfig", "", "absolute path to the kubeconfig file. "+
"If set, this will override the default behavior and "+
"ignore KUBECONFIG environment variable and/or $HOME/.kube/config file location.")
flag.Parse()

var kubeconfig *string
if home := homeDir(); home != "" {
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "absolute path to kubeconfig file")
} else {
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
if *kubeconfigFlag != "" {
loadingRules.ExplicitPath = *kubeconfigFlag
}
flag.Parse()

// use the current context in kubeconfig
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
clientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
restConfig, err := clientConfig.ClientConfig()
if err != nil {
log.Printf("ERROR! Unable to build a valid Kubernetes config, %s", err.Error())
log.Printf("Error during Kubernetes client initialization, %s", err.Error())
os.Exit(1)
}

clientset, err := kubernetes.NewForConfig(config)
dClient, err := discovery.NewDiscoveryClientForConfig(restConfig)
if err != nil {
log.Printf("Error during Kubernetes client initialization, %s", err.Error())
log.Printf("Error during discovery client setup, %s", err.Error())
os.Exit(1)
}

apiResourceListArray, err := clientset.Discovery().ServerResources()
_, apiResourceListArray, err := dClient.ServerGroupsAndResources()
if err != nil {
log.Printf("Error during server resource discovery, %s", err.Error())
os.Exit(1)
}

resourcesByGroupAndVerb := orderedmap.NewOrderedMap()
for _, apiResourceList := range apiResourceListArray {
if enableVerboseLogging {
for _, apiResourceList := range apiResourceListArray {
if *enableVerboseLogging {
log.Printf("Group: %s", apiResourceList.GroupVersion)
}
// rbac rules only look at API group names, not name & version
Expand All @@ -66,7 +64,7 @@ func main() {

resourcesByVerb := make(map[string][]string)
for _, apiResource := range apiResourceList.APIResources {
if enableVerboseLogging {
if *enableVerboseLogging {
log.Printf("Resource: %s - Verbs: %s",
apiResource.Name,
apiResource.Verbs.String())
Expand All @@ -78,10 +76,10 @@ func main() {
}
sort.Strings(verbList)
verbString := strings.Join(verbList[:], ",")
if value,ok := resourcesByVerb[verbString]; ok {
if value, ok := resourcesByVerb[verbString]; ok {
resourcesByVerb[verbString] = append(value, apiResource.Name)
} else {
resourcesByVerb[verbString] = []string {apiResource.Name}
resourcesByVerb[verbString] = []string{apiResource.Name}
}
}

Expand All @@ -90,12 +88,12 @@ func main() {
sb.WriteString(groupOnly)
sb.WriteString("!")
sb.WriteString(k)
if resourceVal,exists := resourcesByGroupAndVerb.Get(sb.String()); exists {
resourceSetMap := make(map[string]bool);
for _,r := range resourceVal.([]string) {
if resourceVal, exists := resourcesByGroupAndVerb.Get(sb.String()); exists {
resourceSetMap := make(map[string]bool)
for _, r := range resourceVal.([]string) {
resourceSetMap[r] = true
}
for _,r := range resourcesByVerb[k] {
for _, r := range resourcesByVerb[k] {
resourceSetMap[r] = true
}
resourceSet := mapSetToList(resourceSetMap)
Expand Down Expand Up @@ -133,12 +131,12 @@ func main() {
APIVersion: "rbac.authorization.k8s.io/v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: roleNameArg,
Name: *roleNameArg,
},
Rules: computedPolicyRules,
}

serializer := k8sJson.NewYAMLSerializer(k8sJson.DefaultMetaFactory, nil, nil)
serializer := k8sJson.NewSerializerWithOptions(k8sJson.DefaultMetaFactory, nil, nil, k8sJson.SerializerOptions{Yaml: true})
var writer = bytes.NewBufferString("")
e := serializer.Encode(completeRbac, writer)
if e != nil {
Expand All @@ -157,10 +155,3 @@ func mapSetToList(initialMap map[string]bool) []string {
}
return list
}

func homeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
return os.Getenv("USERPROFILE") // windows
}
7 changes: 7 additions & 0 deletions tests/k8s.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,10 @@ IFS=$'\n\t'
kube-role-gen | kubeval -
kube-role-gen | kubectl apply --validate -f -
kube-role-gen | conftest test --policy tests/gh-11.rego -

# https://github.com/coopernetes/kube-role-gen/issues/14
if [ -f "$HOME/.kube/config" ]; then
mv $HOME/.kube/config /tmp/test-kubecfg
KUBECONFIG=/tmp/test-kubecfg kube-role-gen
kube-role-gen -kubeconfig /tmp/test-kubecfg
fi

0 comments on commit f79eaf9

Please sign in to comment.