Created
May 26, 2021 21:37
-
-
Save leonsteinhaeuser/c7ffee30911f09a6aa19bd3dd383cdd8 to your computer and use it in GitHub Desktop.
k8s watch custom resource
This file contains 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
package main | |
import ( | |
"context" | |
"fmt" | |
v1 "github.com/programmfabrik/k8s-fylr-operator/api/v1" | |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | |
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" | |
"k8s.io/apimachinery/pkg/runtime" | |
"k8s.io/client-go/dynamic" | |
ctrl "sigs.k8s.io/controller-runtime" | |
) | |
func panicIfError(err error) { | |
if err != nil { | |
panic(err) | |
} | |
} | |
func main() { | |
config, err := ctrl.GetConfig() | |
panicIfError(err) | |
dynamicInterface, err := dynamic.NewForConfig(config) | |
panicIfError(err) | |
// defines a group version resource (gvr) that is used to identify objects within kubernetes. | |
// If the gvr could not be found within kubernetes, the string inside the WithResource function is probably false. | |
groupVersionResource := v1.SchemeBuilder.GroupVersion.WithResource("instances") | |
// watches the specified type | |
watchInterface, err := dynamicInterface.Resource(groupVersionResource).Watch(context.Background(), metav1.ListOptions{ | |
Watch: true, | |
}) | |
panicIfError(err) | |
// receive the channel containing the data consumed by the watcher | |
wch := watchInterface.ResultChan() | |
for { | |
dt := <-wch | |
// convert the runtime.Object to *unstructured.Unstructured | |
// it is not possible to convert this directly to v1.Instance because kubernetes returns an object of type unstructured.Unstructured | |
typeUnstructured := dt.Object.(*unstructured.Unstructured) | |
inst := &v1.Instance{} | |
// finally we can convert the object from the unstructured.Unstructured type to the concrete type | |
err := runtime.DefaultUnstructuredConverter.FromUnstructured(typeUnstructured.UnstructuredContent(), inst) | |
panicIfError(err) | |
// now we can use the instance that contains all the information we provided before | |
fmt.Printf("EventType: %v\nInstance:\n%+v\n\n", dt.Type, inst) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output:
CREATE
UPDATE
DELETE