Skip to content

Commit

Permalink
added funcs to get resources dynamically and with jq
Browse files Browse the repository at this point in the history
Signed-off-by: Thiago Pagotto <pagottoo@gmail.com>
  • Loading branch information
pagottoo committed Jul 19, 2022
1 parent 8100c96 commit 3395922
Showing 1 changed file with 77 additions and 0 deletions.
77 changes: 77 additions & 0 deletions internal/k8s/kubernetes.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,15 @@ import (
"log"
"time"

"github.com/itchyny/gojq"
"github.com/kubefirst/kubefirst/internal/argocd"
"github.com/kubefirst/kubefirst/pkg"
"github.com/spf13/viper"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
coreV1Types "k8s.io/client-go/kubernetes/typed/core/v1"
)

Expand Down Expand Up @@ -100,3 +105,75 @@ func DeleteRegistryApplication(skipDeleteRegistryApplication bool) {
log.Println("skip: deleteRegistryApplication")
}
}

func GetResourcesDynamically(dynamic dynamic.Interface,
ctx context.Context,
group string,
version string,
resource string,
namespace string) (
[]unstructured.Unstructured, error) {

resourceId := schema.GroupVersionResource{
Group: group,
Version: version,
Resource: resource,
}
list, err := dynamic.Resource(resourceId).Namespace(namespace).
List(ctx, metaV1.ListOptions{})

if err != nil {
return nil, err
}

return list.Items, nil
}

func GetResourcesByJq(dynamic dynamic.Interface, ctx context.Context, group string,
version string, resource string, namespace string, jq string) (
[]unstructured.Unstructured, error) {

resources := make([]unstructured.Unstructured, 0)

query, err := gojq.Parse(jq)
if err != nil {
return nil, err
}

items, err := GetResourcesDynamically(dynamic, ctx, group, version, resource, namespace)
if err != nil {
return nil, err
}

for _, item := range items {

// Convert object to raw JSON
var rawJson interface{}
err = runtime.DefaultUnstructuredConverter.FromUnstructured(item.Object, &rawJson)
if err != nil {
return nil, err
}

// Evaluate jq against JSON
iter := query.Run(rawJson)
for {
result, ok := iter.Next()
if !ok {
break
}
if err, ok := result.(error); ok {
if err != nil {
return nil, err
}
} else {
boolResult, ok := result.(bool)
if !ok {
fmt.Println("Query returned non-boolean value")
} else if boolResult {
resources = append(resources, item)
}
}
}
}
return resources, nil
}

0 comments on commit 3395922

Please sign in to comment.