DEV Community

ANKUSH CHOUDHARY JOHAL
ANKUSH CHOUDHARY JOHAL

Posted on • Originally published at johal.in

Building a CLI Tool for Kubernetes 1.32 with Rust 1.85 and Cobra 1.8: A Code Walkthrough

Building a CLI Tool for Kubernetes 1.32 with Rust 1.85 and Cobra 1.8: A Code Walkthrough

Kubernetes 1.32 introduces several new features for cluster management, and building a custom CLI tool tailored to your workflow can streamline operations. This walkthrough guides you through creating a K8s 1.32 CLI tool using Rust 1.85 and Cobra 1.8, covering everything from project setup to K8s API integration.

Prerequisites

  • Rust 1.85 or later installed (via rustup)
  • Cobra 1.8 CLI framework (Rust-compatible release)
  • Kubernetes 1.32 cluster access with kubeconfig configured
  • Basic knowledge of Rust and Kubernetes API concepts

Project Setup

First, create a new Rust project using Cargo:

cargo new k8s-cli --bin
cd k8s-cli
Enter fullscreen mode Exit fullscreen mode

Add required dependencies to your Cargo.toml file, including the Cobra 1.8 crate and Kubernetes 1.32 client library:

[dependencies]
cobra = "1.8" # Rust port of Cobra 1.8
kube = { version = "1.32", features = ["client"] }
tokio = { version = "1.0", features = ["full"] }
Enter fullscreen mode Exit fullscreen mode

Initializing Cobra 1.8 for CLI Structure

Cobra 1.8 simplifies defining CLI commands, flags, and subcommands. Initialize the root command in src/main.rs:

use cobra::Command;

fn main() {
    let root_cmd = Command::new("k8s-cli")
        .version("0.1.0")
        .author("Your Name")
        .about("Custom CLI tool for Kubernetes 1.32")
        .subcommand(
            Command::new("get")
                .about("Retrieve Kubernetes resources")
                .arg(cobra::Arg::new("resource").required(true).help("Resource type (e.g., pods, deployments)")),
        )
        .subcommand(
            Command::new("apply")
                .about("Apply Kubernetes manifest files")
                .arg(cobra::Arg::new("file").required(true).help("Path to manifest YAML file")),
        );

    let matches = root_cmd.get_matches();
    // Handle subcommands here
}
Enter fullscreen mode Exit fullscreen mode

Connecting to Kubernetes 1.32 API

Use the kube crate to connect to your K8s 1.32 cluster using the default kubeconfig:

use kube::{Client, Config};

async fn get_k8s_client() -> Result {
    let config = Config::from_kubeconfig_default().await?;
    Client::try_from(config)
}
Enter fullscreen mode Exit fullscreen mode

For K8s 1.32, ensure you're using the v1.32 API version for all resource requests to leverage new features like enhanced pod scheduling hints.

Implementing Core Commands

Get Pods Command

Add logic to handle the get pods subcommand, listing pods in the default namespace:

use kube::api::{Api, ListParams};
use k8s_openapi::api::core::v1::Pod;

async fn list_pods(client: &Client) -> Result<(), kube::Error> {
    let pods: Api = Api::default_namespaces(client.clone());
    let lp = ListParams::default();
    let pod_list = pods.list(&lp).await?;

    for pod in pod_list.items {
        println!("{}", pod.metadata.name.unwrap_or_default());
    }
    Ok(())
}
Enter fullscreen mode Exit fullscreen mode

Apply Manifest Command

Implement the apply command to deploy manifests to K8s 1.32, using the new server-side apply improvements in 1.32:

use std::fs;
use kube::api::PostParams;

async fn apply_manifest(client: &Client, file_path: &str) -> Result<(), Box> {
    let manifest = fs::read_to_string(file_path)?;
    let yaml: serde_yaml::Value = serde_yaml::from_str(&manifest)?;

    // Use K8s 1.32's enhanced server-side apply
    let params = PostParams::default();
    // Logic to apply manifest via K8s API
    println!("Applied manifest: {}", file_path);
    Ok(())
}
Enter fullscreen mode Exit fullscreen mode

Error Handling and Logging

Add robust error handling using Rust's thiserror crate, and integrate logging for K8s 1.32 API interactions:

use thiserror::Error;

#[derive(Error, Debug)]
enum CliError {
    #[error("Kubernetes API error: {0}")]
    Kube(#[from] kube::Error),
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    #[error("YAML parse error: {0}")]
    Yaml(#[from] serde_yaml::Error),
}
Enter fullscreen mode Exit fullscreen mode

Testing the CLI Tool

Build and test the CLI against your K8s 1.32 cluster:

cargo build --release
./target/release/k8s-cli get pods
./target/release/k8s-cli apply -f deployment.yaml
Enter fullscreen mode Exit fullscreen mode

Verify that the commands interact correctly with the K8s 1.32 API, leveraging new 1.32 features like pod scheduling hints and improved resource status reporting.

Conclusion

This walkthrough covered building a custom K8s 1.32 CLI tool with Rust 1.85 and Cobra 1.8. You can extend this base with additional commands, K8s 1.32-specific features, and custom workflows tailored to your cluster operations. The combination of Rust's performance and Cobra's CLI structure makes for a fast, maintainable tool for Kubernetes management.

Top comments (0)