惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Tenable Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
Threatpost
L
LINUX DO - 热门话题
C
Cyber Attacks, Cyber Crime and Cyber Security
W
WeLiveSecurity
P
Privacy & Cybersecurity Law Blog
H
Hacker News: Front Page
C
Cisco Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Martin Fowler
Martin Fowler
Help Net Security
Help Net Security
Scott Helme
Scott Helme
U
Unit 42
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Cyberwarzone
Cyberwarzone
Microsoft Security Blog
Microsoft Security Blog
月光博客
月光博客
博客园 - 三生石上(FineUI控件)
Cloudbric
Cloudbric
Simon Willison's Weblog
Simon Willison's Weblog
A
Arctic Wolf
云风的 BLOG
云风的 BLOG
V
Vulnerabilities – Threatpost
Stack Overflow Blog
Stack Overflow Blog
T
Tor Project blog
O
OpenAI News
B
Blog RSS Feed
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
The Exploit Database - CXSecurity.com
MyScale Blog
MyScale Blog
罗磊的独立博客
美团技术团队
博客园 - 聂微东
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Apple Machine Learning Research
Apple Machine Learning Research
PCI Perspectives
PCI Perspectives
P
Privacy International News Feed
C
Cybersecurity and Infrastructure Security Agency CISA
Recorded Future
Recorded Future
Application and Cybersecurity Blog
Application and Cybersecurity Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - Franky
Security Archives - TechRepublic
Security Archives - TechRepublic
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Blog — PlanetScale
Blog — PlanetScale

Ivan on Containers, Kubernetes, and Server-Side

A grounded take on agentic coding for production environments Server-Side Playgrounds Reimagined: Build, Boot, and Network Your Own Virtual Labs [not a] Kubernetes 101 - Pods, Deployments, and Services As an Attempt To Automate Age-Old Infra Patterns JavaScript or TypeScript? How To Benefit From the Dichotomy On Software Design... and Good Writing Building a Firecracker-Powered Course Platform To Learn Docker and Kubernetes How To Publish a Port of a Running Container What Actually Happens When You Publish a Container Port A Visual Guide to SSH Tunnels: Local and Remote Port Forwarding Debugging Containers Like a Pro Docker: How To Debug Distroless And Slim Containers How To Extract Container Image Filesystem Using Docker | iximiuz Labs In Pursuit of Better Container Images: Alpine, Distroless, Apko, Chisel, DockerSlim, oh my! How To Start Programming In Go: Advice For Fellow DevOps Engineers Kubernetes Ephemeral Containers and kubectl debug Command Docker Container Commands Explained: Understand, Don't Memorize | iximiuz Labs Learning Docker with Docker - Toying With DinD For Fun And Profit How To Extend Kubernetes API - Kubernetes vs. Django The Influence of Plumbing on Programming How To Call Kubernetes API from Go - Types and Common Machinery How To Call Kubernetes API using Simple HTTP Client Kubernetes API Basics - Resources, Kinds, and Objects OpenFaaS - Run Containerized Functions On Your Own Terms Learning Containers From The Bottom Up Docker Containers vs. Kubernetes Pods - Taking a Deeper Look | iximiuz Labs Learn-by-Doing Platforms for Dev, DevOps, and SRE Folks How HTTP Keep-Alive can cause TCP race condition How to Work with Container Images Using ctr | iximiuz Labs Multiple Containers, Same Port, no Reverse Proxy... Exploring Go net/http Package - On How Not To Set Socket Options Disposable Local Development Environments with Vagrant, Docker, and Arkade DevOps, SRE, and Platform Engineering My Choice of Programming Languages Prometheus Is Not a TSDB How to learn PromQL with Prometheus Playground Prometheus Cheat Sheet - Basics (Metrics, Labels, Time Series, Scraping) Rust - Writing Parsers With nom Parser Combinator Framework pq - parse and query log files as time series Prometheus Cheat Sheet - Moving Average, Max, Min, etc (Aggregation Over Time) Prometheus Cheat Sheet - How to Join Multiple Metrics (Vector Matching) The Need For Slimmer Containers Understanding Rust Privacy and Visibility Model Bridge vs. Switch: Takeaways from a Real Data Center Tour | iximiuz Labs From LAN to VXLAN: Networking Basics for Non-Network Engineers | iximiuz Labs KiND - How I Wasted a Day Loading Local Docker Images Go, HTTP handlers, panic, and deadlocks Exploring Kubernetes Operator Pattern Making Sense Out Of Cloud Native Buzz Service Discovery in Kubernetes: Combining the Best of Two Worlds API Developers Never REST How Container Networking Works: Building a Bridge Network From Scratch | iximiuz Labs Traefik: canary deployments with weighted load balancing Service Proxy, Pod, Sidecar, oh my! You Need Containers To Build Images You Don't Need an Image To Run a Container Not Every Container Has an Operating System Inside Working with container images in Go Master Go While Learning Containers Implementing Container Runtime Shim: Interactive Containers How to use Flask with gevent (uWSGI and Gunicorn editions) My 10 Years of Programming Experience Implementing Container Runtime Shim: First Code Implementing Container Runtime Shim: runc Kubernetes Repository On Flame Dealing with process termination in Linux (with Rust examples) conman - [the] Container Manager: Inception Journey From Containerization To Orchestration And Beyond Linux PTY - How docker attach and docker exec Commands Work Inside Illustrated introduction to Linux iptables From Docker Container to Bootable Linux Disk Image Пишем свой веб-сервер на Python: протокол HTTP 9001 способ создать веб-сервер на Python Explaining async/await in 200 lines of code Explaining event loop in 100 lines of code Save the day with gevent Пишем свой веб-сервер на Python: процессы, потоки и асинхронный I/O Truly optional scalar types in protobuf3 (with Go examples) Node.js Writable streams distilled Node.js Readable streams distilled How to on starting processes (mostly in Linux) Дайджест интересных ссылок – Июль 2016 Пишем свой веб-сервер на Python: сокеты Наследование в JavaScript Мастерить!
How To Develop Kubernetes CLIs Like a Pro
Ivan Velichko · 2022-05-14 · via Ivan on Containers, Kubernetes, and Server-Side

A short one today. Just wanted you to meet my new favorite Go library to work with Kubernetes - k8s.io/cli-runtime. It's probably the most underappreciated package in the whole k8s.io/* family based on its value to the number of stars ratio.

Here is what the README file says about it:

Set of helpers for creating kubectl commands, as well as kubectl plugins.

This library is a shared dependency for clients to work with Kubernetes
API infrastructure which allows to maintain kubectl compatible behavior.

If the above description didn't sound too impressive, let me try to decipher it for you - with the cli-runtime library, you can write CLI tools that behave like and are as potent as the mighty kubectl!

Here is what you actually can achieve with just a few lines of code using the cli-runtime library:

  • Register the well-know flags like --kubeconfig|--context|--namespace|--server|--token|... and pass their values to one or more client-go instances.
  • Look up cluster objects by their resources, kinds, and names with the full-blown support of familiar shortcuts like deploy for deployments or po for pods.
  • Read and kustomize YAML/JSON Kubernetes manifests into the corresponding Go structs.
  • Pretty-print Kubernetes objects as YAML, JSON (with JSONPath support), and even human-readable tables!

Interested? Then have a look at the usage examples below 😉

Create Kubernetes Clients From Command-Line Flags

The de-facto standard solution for the command-line flags processing in Go is cobra. The k8s.io/cli-runtime library embraces it and builds its functionality on top of cobra.

Here is a mini-program that uses typical Kubernetes CLI flags to create a client-go instance for further Kubernetes API access:

package main

import (
    "fmt"

    "github.com/spf13/cobra"
    "k8s.io/cli-runtime/pkg/genericclioptions"
    "k8s.io/client-go/kubernetes"
)

func main() {
    // 1. Create a flags instance.
    configFlags := genericclioptions.NewConfigFlags(true)

    // 2. Create a cobra command.
    cmd := &cobra.Command{
        Use: "kubectl (well, almost)",
        Run: func(cmd *cobra.Command, args []string) {

            // 4. Get client config from the flags.
            config, _ := configFlags.ToRESTConfig()

            // 5. Create a client-go instance for config.
            client, _ := kubernetes.NewForConfig(config)

            vinfo, _ := client.Discovery().ServerVersion()
            fmt.Println(vinfo)
        },
    }

    // 3. Register flags with cobra.
    configFlags.AddFlags(cmd.PersistentFlags())

    _ = cmd.Execute()
}

Now, let's see what flags are available:

$ go run main.go --help
Usage:
  kubectl (well, almost) [flags]

Flags:
      --as string                      Username to impersonate for the operation. User could be a regular user or a service account in a namespace.
      --as-group stringArray           Group to impersonate for the operation, this flag can be repeated to specify multiple groups.
      --as-uid string                  UID to impersonate for the operation.
      --cache-dir string               Default cache directory (default "/home/vagrant/.kube/cache")
      --certificate-authority string   Path to a cert file for the certificate authority
      --client-certificate string      Path to a client certificate file for TLS
      --client-key string              Path to a client key file for TLS
      --cluster string                 The name of the kubeconfig cluster to use
      --context string                 The name of the kubeconfig context to use
  -h, --help                           help for kubectl
      --insecure-skip-tls-verify       If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure
      --kubeconfig string              Path to the kubeconfig file to use for CLI requests.
  -n, --namespace string               If present, the namespace scope for this CLI request
      --request-timeout string         The length of time to wait before giving up on a single server request. Non-zero values should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests. (default "0")
  -s, --server string                  The address and port of the Kubernetes API server
      --tls-server-name string         Server name to use for server certificate validation. If it is not provided, the hostname used to contact the server is used
      --token string                   Bearer token for authentication to the API server
      --user string                    The name of the kubeconfig user to use

Quite powerful, isn't it? And only 3 lines of code (well, 4 with the import line) were needed.

Search For Cluster Objects Like a Boss

You probably know that kubectl employs a bunch of tricks to make working with resources a bit more user-friendly:

# Get resources using shortcuts
$ kubectl get po
$ kubectl get pods
$ kubectl get cm
$ kubectl get configmaps

# Get resources by singular and plural names
$ kubectl get service
$ kubectl get services

# Get multiple resource types at once
$ kubectl get po,deploy,svc

# Search by kind instead of resource name
$ kubectl get ServiceAccount

# Get an object by name
$ kubectl get service kubernetes
$ kubectl get service/kubernetes
$ kubectl get svc kubernetes
$ kubectl get svc/kubernetes

# Get resources from all namespaces
$ kubectl get pods --all-namespaces

Turns out, this handiness is actually implemented by the cli-runtime library, and it's fully reusable! You just need to instantiate a resource.Builder and let it parse the command-line argument(s) for you:

package main

import (
    "fmt"
    "os"

    "github.com/spf13/cobra"
    "k8s.io/cli-runtime/pkg/genericclioptions"
    "k8s.io/cli-runtime/pkg/resource"
    "k8s.io/client-go/kubernetes/scheme"
)

func main() {
    // Already familiar stuff...
    configFlags := genericclioptions.NewConfigFlags(true)

    cmd := &cobra.Command{
        Use: "kubectl (even closer to it this time)",
        Args: cobra.MinimumNArgs(1),
        Run: func(cmd *cobra.Command, args []string) {

            // Our hero - The Resource Builder.
            builder := resource.NewBuilder(configFlags)

            namespace := ""
            if configFlags.Namespace != nil {
                namespace = *configFlags.Namespace
            }

            // Let the Builder do all the heavy-lifting.
            obj, _ := builder.
                // Scheme teaches the Builder how to instantiate resources by names.
                WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
                // Where to look up.
                NamespaceParam(namespace).
                // What to look for.
                ResourceTypeOrNameArgs(true, args...).
                // Do look up, please.
                Do().
                // Convert the result to a runtime.Object
                Object()

            fmt.Println(obj)
        },
    }

    configFlags.AddFlags(cmd.PersistentFlags())

    _ = cmd.Execute()
}

Now you can use the above mini-program much like the kubectl get command:

$ go run main.go --help
$ go run main.go po
$ go run main.go pod
$ go run main.go pods
$ go run main.go services,deployments
$ go run main.go --namespace=default service/kubernetes
$ go run main.go --namespace default service kubernetes

Interesting that the actual magic happens not so much in the builder itself but rather in the Scheme and RESTMapper modules. These are two tenants of another Kubernetes wonderful Go library called k8s.io/apimachinery. Both are kinda sorta registries utilizing the Kubernetes API Discovery information - the Scheme maps object kinds to Go structs representing Kubernetes Objects, and the RESTMapper maps resource names to kinds and vice versa.

Kubernetes RESTMapper and runtime.Scheme

Another interesting exemplar in the above mini-program is the runtime.Object returned by the Builder. It's a generic interface to abstract a concrete k8s.io/api struct representing a certain Kubernetes object (like Pod, Deployment, ConfigMap, etc.):

How to represent data structures from Kubernetes manifests as Go types.

You can read more about Objects, Schemes, and Mappers in my previous article:

👉 How To Call Kubernetes API from Go - Types and Common Machinery

Read Kubernetes Manifests Into Go Structs

Much like with searching for cluster objects, the resource.Builder can be used to read YAML/JSON Kubernetes manifests from files, URLs, or even the stdin. The only difference is the method used to point the builder to the data source - instead of ResourceTypeOrNameArgs(), you'd need to call the method FilenameParam() supplying a resource.FilenameOptions{Filenames []string, Recursive bool, Kustomize bool} parameter:

package main

import (
    "os"

    "github.com/spf13/cobra"
    "k8s.io/cli-runtime/pkg/genericclioptions"
    "k8s.io/cli-runtime/pkg/resource"
    "k8s.io/client-go/kubernetes/scheme"
)

func main() {
    configFlags := genericclioptions.NewConfigFlags(true)

    cmd := &cobra.Command{
        Use:  "kubectl (not really)",
        Args: cobra.MinimumNArgs(1),
        Run: func(cmd *cobra.Command, args []string) {
            builder := resource.NewBuilder(configFlags)

            namespace := ""
            if configFlags.Namespace != nil {
                namespace = *configFlags.Namespace
            }
            enforceNamespace := namespace != ""

            _ = builder.
                WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
                NamespaceParam(namespace).
                DefaultNamespace().
                FilenameParam(
                    enforceNamespace,
                    &resource.FilenameOptions{Filenames: args},
                ).
                Do().
                Visit(func(info *resource.Info, _ error) error {
                    fmt.Println(info.Object)
                    return nil
                })
        },
    }

    configFlags.AddFlags(cmd.PersistentFlags())

    _ = cmd.Execute()
}

If the additional namespace parameter is provided and (some) objects in the manifests miss the namespace, it'll be populated from that parameter. The enforceNamespace flag can be used to make the builder fail if the supplied namespace value differs from the (explicitly set) values in the manifest(s).

Pretty-Print Kubernetes Object as YAML/JSON/Tables

If you tried the above mini-programs, you probably noticed how poor was the output formatting. Luckily, the cli-runtime library has a bunch of (pretty-)printers that can be used to dump Kubernetes objects as YAML, JSON, or even human-readable tables:

package main

import (
    "fmt"
    "os"

    corev1 "k8s.io/api/core/v1"
    "k8s.io/cli-runtime/pkg/printers"
    "k8s.io/client-go/kubernetes/scheme"
)

func main() {
    obj := &corev1.ConfigMap{
        Data: map[string]string{"foo": "bar"},
    }
    obj.Name = "my-cm"

    // YAML
    fmt.Println("# YAML ConfigMap representation")
    printr := printers.NewTypeSetter(scheme.Scheme).ToPrinter(&printers.YAMLPrinter{})
    if err := printr.PrintObj(obj, os.Stdout); err != nil {
        panic(err.Error())
    }

    fmt.Println()

    // JSON
    fmt.Println("# JSON ConfigMap representation")
    printr = printers.NewTypeSetter(scheme.Scheme).ToPrinter(&printers.JSONPrinter{})
    if err := printr.PrintObj(obj, os.Stdout); err != nil {
        panic(err.Error())
    }

    fmt.Println()

    // Table (human-readable)
    fmt.Println("# Table ConfigMap representation")
    printr = printers.NewTypeSetter(scheme.Scheme).ToPrinter(printers.NewTablePrinter(printers.PrintOptions{}))
    if err := printr.PrintObj(obj, os.Stdout); err != nil {
        panic(err.Error())
    }

    fmt.Println()

    // JSONPath
    fmt.Println("# ConfigMap.data.foo")
    printr, err := printers.NewJSONPathPrinter("{.data.foo}")
    if err != nil {
        panic(err.Error())
    }

    printr = printers.NewTypeSetter(scheme.Scheme).ToPrinter(printr)
    if err := printr.PrintObj(obj, os.Stdout); err != nil {
        panic(err.Error())
    }

    fmt.Println()

    // Name-only
    fmt.Println("# <kind>/<name>")
    printr = printers.NewTypeSetter(scheme.Scheme).ToPrinter(&printers.NamePrinter{})
    if err := printr.PrintObj(obj, os.Stdout); err != nil {
        panic(err.Error())
    }

    fmt.Println()
}

Notice how all the PrintObj() methods accept the already familiar runtime.Object type making the printing functionality generic.

More examples

Congrats! Now you're well-armed to start writing your own Kubernetes CLIs! Feel otherwise? 🙈 Then check out more mini-programs from my extended client-go collection on GitHub 😉

Good luck!