RestMapper In Go

utsab sapkotautsab sapkota
3 min read

Initialize the go project

go mod init github.com/<your-username>/<project-name>

Import the required packages

package main

import (
    "flag"
    "fmt"

    "k8s.io/apimachinery/pkg/runtime/schema"
    "k8s.io/cli-runtime/pkg/genericclioptions"
    cmdutil "k8s.io/kubectl/pkg/cmd/util"
)
    • flag: This package provides a simple way to parse command-line arguments (flags) in Go.

      • fmt: This package provides formatting functions for printing output to the console.

      • k8s.io/apimachinery/pkg/runtime/schema: This package provides types and utilities for working with Kubernetes API resource schemas. It's often used for dealing with resource identifiers and metadata.

      • k8s.io/cli-runtime/pkg/genericclioptions: This package provides generic options for Kubernetes CLI tools. It abstracts away some common functionality needed by CLI tools.

      • k8s.io/kubectl/pkg/cmd/util: This package provides utility functions for various kubectl commands. It's used for tasks such as creating REST clients, executing commands, and handling resource mapping.

Use those packages to extract GVR

func main() {
    var res string
    flag.StringVar(&res, "res", "", "resource that you want to interact with")
    flag.Parse()
  • The main() function is the entry point of the program.

  • It defines a string variable res to hold the name of the Kubernetes resource specified by the user.

  • It uses flag.StringVar() to define a command-line flag -res that accepts a string value. The value provided by the user will be stored in the res variable.

  • flag.Parse() is called to parse the command-line flags provided when the program is executed.

    configFlag := genericclioptions.NewConfigFlags(true).WithDeprecatedPasswordFlag()
  • This line creates configuration flags for Kubernetes CLI operations.

  • genericclioptions.NewConfigFlags(true) creates a new set of configuration flags. The true argument indicates that default flags should be included.

  • WithDeprecatedPasswordFlag() adds a deprecated password flag to the configuration flags. This flag is likely related to authentication options.

    matchVersionFlags := cmdutil.NewMatchVersionFlags(configFlag)
  • This line creates match version flags.

  • cmdutil.NewMatchVersionFlags() creates new match version flags based on the provided configuration flags. These flags are used for handling Kubernetes API version matching.

    factory := cmdutil.NewFactory(matchVersionFlags)
  • This line creates a factory object for creating various Kubernetes clients and other objects.

  • cmdutil.NewFactory() creates a new factory based on the provided match version flags. This factory is used to create REST clients, resource clients, and other Kubernetes-related objects.

    m, err := factory.ToRESTMapper()
    if err != nil {
        fmt.Printf("getting REST mapper from factory: %s\n", err.Error())
        return
    }
  • This line obtains the REST mapper from the factory object.

  • factory.ToRESTMapper() returns the REST mapper. The REST mapper is used to map resource types to their corresponding API endpoints.

  • If an error occurs during the retrieval of the REST mapper, an error message is printed, and the program exits.

    gvr, err := m.ResourceFor(schema.GroupVersionResource{
        Resource: res,
    })
    if err != nil {
        fmt.Printf("getting GVR for resource: %s\n", err.Error())
        return
    }
    fmt.Printf("Complete GVR is, group %s, version %s, resource %s\n", gvr.Group, gvr.Version, gvr.Resource)
}
  • This section gets the GroupVersionResource (GVR) for the specified resource.

  • m.ResourceFor() retrieves the GVR for the specified resource from the REST mapper.

  • If an error occurs during the retrieval of the GVR, an error message is printed, and the program exits.

  • If successful, the group, version, and resource of the GVR are printed to the console.

Overall Code:

package main

import (
    "flag"
    "fmt"

    "k8s.io/apimachinery/pkg/runtime/schema"
    "k8s.io/cli-runtime/pkg/genericclioptions"
    cmdutil "k8s.io/kubectl/pkg/cmd/util"
)

func main() {
    // res := "pods"

    var res string
    flag.StringVar(&res, "res", "", "resource that you want to interact with")
    flag.Parse()

    configFlag := genericclioptions.NewConfigFlags(true).WithDeprecatedPasswordFlag()
    matchVersionFlags := cmdutil.NewMatchVersionFlags(configFlag)
    m, err := cmdutil.NewFactory(matchVersionFlags).ToRESTMapper()
    if err != nil {
        fmt.Printf("getting rest mapper from newfactory %s\n", err.Error())
    }

    gvr, err := m.ResourceFor(schema.GroupVersionResource{
        Resource: res,
    })
    if err != nil {
        fmt.Printf("getting GVR for resource %s\n", err.Error())
    }
    fmt.Printf("Complete GVR is, group %s, version %s, resource %s\n", gvr.Group, gvr.Version, gvr.Resource)
}

Output of the code:

After building the project using go build

Here Group = "", Version = v1, Resource = pods (for pods)

For storageclasses, Group Version Resource is
Group = storage.k8s.io , Version = v1 and Resource = storageclasses

0
Subscribe to my newsletter

Read articles from utsab sapkota directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

utsab sapkota
utsab sapkota