Kubernetes - Development

Last Updated: 2023-01-15

How to get the client?

You need a client to talk to the k8s cluster.

In controller-runtime: client.Client is defined in sigs.k8s.io/controller-runtime/pkg/client

controller-runtime depends on client-go. There 2 types of clients:

  • typed: k8s.io/client-go/kubernets.ClientSet
  • dynamic: k8s.io/client-go/dynamic.Interface

kubeconfig => clientSet

bytesArray := []byte(*kubeconfig)

clientConfig ,err:= clientcmd.NewClientConfigFromBytes(bytesArray)
if err!=nil {
	return nil

restConfig, _ := clientConfig.ClientConfig()
clientSet, err := kubernetes.NewForConfig(restConfig)

kubeconfig => dynamic client

dynamic client has no knowledge about the resource you want to consume

config, err := rest.InClusterConfig()
if err != nil {
    return nil, err

dynClient, err := dynamic.NewForConfig(config)
if err != nil {
    return nil, err

How to create new obj?

import "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"

obj = &foo.Bar{
    ObjectMeta: metav1.ObjectMeta{
        Name:      "name",
        Namespace:  "namespace",
controllerutil.CreateOrUpdate(ctx, client, obj, func () error {
    // mutation logic, i.e. modify obj based on existing states.

How to update status?

client.Status().Update(ctx, obj)

How to get object key?


How to retry?

retry.RetryOnConflict(retryBackoff, func() error {

How to get kubeconfig from secrets?

capiconfig "sigs.k8s.io/cluster-api/util/kubeconfig"

nn := types.NamespacedName{
  Name: consts.RootAdminClusterName,
  Namespace: consts.RootAdminClusterNamespace,
kubeconfig, err := capiconfig.FromSecret(ctx, client, nn)

Client Getter to Client

clientConfig, err := clientGetter.ToRESTConfig()
if err != nil {
    return err
client, err := client.New(clientConfig, client.Options{})
if err != nil {
    return err