Kubernetes CLI-Runtime Explained
About 997 words
k8s.io/cli-runtime is an official Kubernetes Go library for building Kubernetes command-line tools. It provides core runtime functionality for tools such as kubectl, including resource discovery, object operations, and output formatting.
What Is CLI-Runtime?
CLI-Runtime is an important component of the Kubernetes ecosystem. It provides:
- A unified command-line interface: A consistent command-line experience across Kubernetes tools.
- Resource discovery: Automatic discovery of API resources and versions in a cluster.
- Object operation abstractions: Consistent operations for creating, reading, updating, and deleting resources.
- Output formatting: Multiple output formats, including JSON, YAML, and tables.
- Configuration management: Handling kubeconfig files and authentication.
Core Components
1. RESTClient and DynamicClient
import (
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/cli-runtime/pkg/resource"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/rest"
)
// Create the configuration
configFlags := genericclioptions.NewConfigFlags(true)
config, err := configFlags.ToRESTConfig()
if err != nil {
return err
}
// Create a dynamic client
dynamicClient, err := dynamic.NewForConfig(config)
if err != nil {
return err
}2. Resource Builder
import "k8s.io/cli-runtime/pkg/resource"
// Create a resource builder
builder := resource.NewBuilder(configFlags).
Unstructured().
ContinueOnError().
Local().
Flatten()
// Read resources from a file
result := builder.FilenameParam(false, &resource.FilenameOptions{
Recursive: false,
Filenames: []string{"deployment.yaml"},
}).Do()
// Retrieve resource objects
infos, err := result.Infos()
if err != nil {
return err
}3. Output Formatting
import "k8s.io/cli-runtime/pkg/printers"
// Create a printer
printer := &printers.YAMLPrinter{}
// Print resources
for _, info := range infos {
if err := printer.PrintObj(info.Object, os.Stdout); err != nil {
return err
}
}Usage Examples
Basic Usage
package main
import (
"fmt"
"os"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/cli-runtime/pkg/resource"
"k8s.io/cli-runtime/pkg/printers"
)
func main() {
// 1. Create configuration flags
configFlags := genericclioptions.NewConfigFlags(true)
// 2. Get the REST configuration
config, err := configFlags.ToRESTConfig()
if err != nil {
fmt.Printf("Error getting config: %v\n", err)
os.Exit(1)
}
// 3. Create a resource builder
builder := resource.NewBuilder(configFlags).
Unstructured().
ContinueOnError().
Local().
Flatten()
// 4. Read resources from a file
result := builder.FilenameParam(false, &resource.FilenameOptions{
Recursive: false,
Filenames: []string{"deployment.yaml"},
}).Do()
// 5. Retrieve resource information
infos, err := result.Infos()
if err != nil {
fmt.Printf("Error getting infos: %v\n", err)
os.Exit(1)
}
// 6. Print resources
printer := &printers.YAMLPrinter{}
for _, info := range infos {
fmt.Printf("Resource: %s/%s\n", info.Namespace, info.Name)
if err := printer.PrintObj(info.Object, os.Stdout); err != nil {
fmt.Printf("Error printing object: %v\n", err)
}
}
}Dynamic Resource Operations
import (
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// Create a dynamic client
dynamicClient, err := dynamic.NewForConfig(config)
if err != nil {
return err
}
// Define the group, version, and resource
gvr := schema.GroupVersionResource{
Group: "apps",
Version: "v1",
Resource: "deployments",
}
// Retrieve the resource
obj, err := dynamicClient.Resource(gvr).
Namespace("default").
Get(context.TODO(), "my-deployment", metav1.GetOptions{})
if err != nil {
return err
}
// Modify the resource
unstructuredObj := obj.(*unstructured.Unstructured)
unstructured.SetNestedField(unstructuredObj.Object, 3, "spec", "replicas")
// Update the resource
_, err = dynamicClient.Resource(gvr).
Namespace("default").
Update(context.TODO(), unstructuredObj, metav1.UpdateOptions{})
if err != nil {
return err
}How It Works
1. Resource Discovery
CLI-Runtime discovers resources in a cluster through the following steps:
// 1. Retrieve the API group list
apiGroups, err := discoveryClient.ServerGroups()
if err != nil {
return err
}
// 2. Retrieve resources in each group
for _, group := range apiGroups.Groups {
groupVersion := group.PreferredVersion.GroupVersion
resources, err := discoveryClient.ServerResourcesForGroupVersion(groupVersion)
if err != nil {
continue
}
// Process resources
for _, resource := range resources.APIResources {
// Construct the GVR
gvr := schema.GroupVersionResource{
Group: group.Name,
Version: groupVersion,
Resource: resource.Name,
}
}
}2. The Resource Builder Pattern
Resource Builder uses the builder pattern to construct resource operations:
type Builder struct {
configFlags *genericclioptions.ConfigFlags
unstructured bool
continueOnError bool
local bool
flatten bool
filenames []string
}
func (b *Builder) Unstructured() *Builder {
b.unstructured = true
return b
}
func (b *Builder) FilenameParam(recursive bool, options *FilenameOptions) *Builder {
b.filenames = options.Filenames
return b
}
func (b *Builder) Do() *Result {
// Execute resource-building logic
return &Result{builder: b}
}3. Output Formatting System
CLI-Runtime provides a flexible printing system:
type Printer interface {
PrintObj(obj runtime.Object, w io.Writer) error
}
// Built-in printer types
type JSONPrinter struct{}
type YAMLPrinter struct{}
type TablePrinter struct{}
type NamePrinter struct{}Advanced Features
1. Custom Resource Support
// Register custom resources
scheme := runtime.NewScheme()
scheme.AddKnownTypes(schema.GroupVersion{
Group: "mycompany.com",
Version: "v1",
}, &MyCustomResource{})
// Use a custom scheme
codecFactory := serializer.NewCodecFactory(scheme)
decoder := codecFactory.UniversalDecoder()2. Batch Operations
// Create resources in a batch
visitor := resource.NewFlattenListVisitor(infos, resourceMapper)
err := visitor.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
// Create the resource
obj, err := resource.NewHelper(info.Client, info.Mapping).
Create(info.Namespace, true, info.Object)
if err != nil {
return err
}
info.Refresh(obj, true)
return nil
})3. Error Handling
// Continue processing after errors
builder := resource.NewBuilder(configFlags).
ContinueOnError() // Continue processing other resources if an error occurs
result := builder.Do()
errs := []error{}
err := result.Visit(func(info *resource.Info, err error) error {
if err != nil {
errs = append(errs, err)
return nil // Continue processing
}
// Process the resource
return nil
})
// Handle all errors
if len(errs) > 0 {
for _, err := range errs {
fmt.Printf("Error: %v\n", err)
}
}Best Practices
1. Configuration Management
// Use environment variables and configuration files
configFlags := genericclioptions.NewConfigFlags(true)
configFlags.AddFlags(flagSet)
// Support multiple configuration sources
// 1. Command-line arguments
// 2. Environment variables
// 3. kubeconfig files
// 4. In-cluster configuration2. Resource Validation
// Validate the resource
validator := validation.NewSchemaValidator(schema, nil, nil, false)
errs := validator.Validate(obj)
if len(errs) > 0 {
return fmt.Errorf("validation failed: %v", errs)
}3. Concurrent Processing
// Use a worker pool to process a large number of resources
type Worker struct {
id int
workChan <-chan *resource.Info
resultChan chan<- error
}
func (w *Worker) process() {
for info := range w.workChan {
err := w.processResource(info)
w.resultChan <- err
}
}Summary
k8s.io/cli-runtime is a core library for building Kubernetes command-line tools. It provides:
- A unified interface: A consistent development experience across K8s tools.
- Resource abstractions: Simpler operations on Kubernetes resources.
- Flexible configuration: Multiple configuration methods and authentication mechanisms.
- Powerful output: Various output formats and customization options.
- Error handling: Comprehensive error handling and recovery mechanisms.
With CLI-Runtime, developers can quickly build powerful, user-friendly Kubernetes command-line tools without dealing with complex implementation details underneath.