Below is an example of a simple Rust client that uses the kube crate to interact with Kubernetes. This example shows how to list pods (by default in the "default" namespace, or you can specify a namespace) and list all namespaces. You can extend this code to perform more actions as needed.
1. Create a New Cargo Project
bash
cargo new simple_kube_client
cd simple_kube_client
2. Update Cargo.toml
Add the following dependencies to your Cargo.toml file:
toml
[dependencies]
kube = { version = "0.84.0", features = ["derive"] }
k8s-openapi = "0.17.0"
tokio = { version = "1.28", features = ["macros"] }
Note: The version numbers may change over time; please refer to crates.io for the latest versions.
3. Write the Client Code
Replace the contents of src/main.rs with the following code:
rust
use kube::{api::ListParams, Api, Client};
use k8s_openapi::api::core::v1::{Namespace, Pod};
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Collect command-line arguments. Usage:
// cargo run -- pods [namespace]
// cargo run -- namespaces
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
eprintln!("Usage: {} [pods|namespaces] [optional: namespace]", args[0]);
std::process::exit(1);
}
let command = args[1].as_str();
// Create a Kubernetes client using in-cluster config or kubeconfig.
let client = Client::try_default().await?;
match command {
"pods" => {
// Use a provided namespace or fallback to "default"
let namespace = if args.len() > 2 { args[2].as_str() } else { "default" };
println!("Listing pods in namespace: {}", namespace);
let pods: Api<Pod> = Api::namespaced(client, namespace);
let lp = ListParams::default();
// List pods and print each pod's name
match pods.list(&lp).await {
Ok(pod_list) => {
for pod in pod_list {
if let Some(name) = pod.metadata.name {
println!(" - {}", name);
}
}
}
Err(e) => eprintln!("Error listing pods: {}", e),
}
}
"namespaces" => {
println!("Listing all namespaces");
let namespaces: Api<Namespace> = Api::all(client);
let lp = ListParams::default();
// List namespaces and print each namespace's name
match namespaces.list(&lp).await {
Ok(ns_list) => {
for ns in ns_list {
if let Some(name) = ns.metadata.name {
println!(" - {}", name);
}
}
}
Err(e) => eprintln!("Error listing namespaces: {}", e),
}
}
_ => {
eprintln!("Unsupported command. Use 'pods' or 'namespaces'.");
}
}
Ok(())
}
4. Running the Client
Assuming you have access to your Kubernetes cluster (either via in-cluster configuration or with a valid kubeconfig file), you can run the client:
List pods (in the default namespace):
bash
cargo run -- pods
List pods in a specific namespace (e.g., "my-namespace"):
bash
cargo run -- pods my-namespace
List all namespaces:
bash
cargo run -- namespaces
5. Extend to "Basic Things"
The above code demonstrates a couple of basic operations (listing pods and namespaces). You can build upon this by:
Creating or Deleting Resources: Use the Api::create, Api::delete, etc., methods to manage Kubernetes resources.
Watching Resources: Use watcher from the kube-runtime module to monitor for changes.
Interacting with Other API Groups: Replace k8s_openapi::api::core::v1 with other API groups for deployments, services, etc.
With these building blocks, you now have a simple Rust-based Kubernetes client to interact with your cluster!