Last active
February 20, 2022 02:56
-
-
Save jsnouffer/362eed71768646945845de4316fe24f0 to your computer and use it in GitHub Desktop.
API Machinery unstructured package
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"context" | |
"fmt" | |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | |
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" | |
"k8s.io/apimachinery/pkg/runtime/schema" | |
"k8s.io/client-go/dynamic" | |
ctrl "sigs.k8s.io/controller-runtime" | |
) | |
func main() { | |
ctx := context.Background() | |
config := ctrl.GetConfigOrDie() | |
dynamic := dynamic.NewForConfigOrDie(config) | |
namespace := "default" | |
items, err := GetResourcesDynamically(dynamic, ctx, | |
"apps", "v1", "deployments", namespace) | |
if err != nil { | |
fmt.Println(err) | |
} else { | |
for _, item := range items { | |
fmt.Printf("%+v\n", item) | |
} | |
} | |
} | |
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment