Here's a simple Rust client for Kubernetes using the kube crate, which is the most commonly used Kubernetes client in Rust. This example demonstrates how to:
- List pods in a namespace
- Get a specific pod
- Create a simple pod
- Delete a pod
✅ Prerequisites
Make sure you have:
- Rust installed (
rustc and cargo)
- A running Kubernetes cluster (e.g., Minikube or Kind)
- Proper kubeconfig set up (
~/.kube/config)
📦 Cargo.toml
Add this to your Cargo.toml:
[dependencies]
kube = "0.85"
k8s-openapi = { version = "0.18", default-features = false, features = ["v1Pod"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
🧾 main.rs
use kube::{Client, Api, config};
use k8s_openapi::api::core::v1::Pod;
use serde::Deserialize;
use std::collections::HashMap;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Load Config
let kubeconfig = config::load_kube_config().await?;
let client = Client::try_from(kubeconfig)?;
// Namespace to operate on
let namespace = "default";
// Access the Pod API
let pods: Api<Pod> = Api::namespaced(client.clone(), namespace);
println!("Listing pods in namespace {}", namespace);
list_pods(&pods).await?;
// Uncomment to create and delete a test pod
// let pod_name = "test-pod";
// create_pod(&pods, pod_name).await?;
// get_pod(&pods, pod_name).await?;
// delete_pod(&pods, pod_name).await?;
Ok(())
}
async fn list_pods(pods: &Api<Pod>) -> Result<(), kube::Error> {
let pod_list = pods.list(&Default::default()).await?;
for p in pod_list.items {
println!(" - {}", p.metadata.name.unwrap());
}
Ok(())
}
async fn create_pod(pods: &Api<Pod>, name: &str) -> Result<(), kube::Error> {
println!("Creating pod {}", name);
let mut annotations = HashMap::new();
annotations.insert("created-with", "rust-kube");
let pod = serde_json::json!({
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"name": name,
"annotations": annotations
},
"spec": {
"containers": [{
"name": "busybox",
"image": "busybox",
"command": ["sh", "-c", "echo 'Hello from Rust'; sleep 3600"],
"imagePullPolicy": "IfNotPresent"
}]
}
});
let params = kube::api::PostParams::default();
let _pod = pods.create(¶ms, &pod).await?;
println!("Pod {} created", name);
Ok(())
}
async fn get_pod(pods: &Api<Pod>, name: &str) -> Result<(), kube::Error> {
println!("Getting pod {}", name);
let pod = pods.get(name).await?;
println!("Pod IP: {:?}", pod.status.as_ref().and_then(|s| s.pod_ip.clone()));
Ok(())
}
async fn delete_pod(pods: &Api<Pod>, name: &str) -> Result<(), kube::Error> {
println!("Deleting pod {}", name);
let params = kube::api::DeleteParams::default();
pods.delete(name, ¶ms).await?.map_or(Ok(()), |status| {
if status.reason == Some("NotFound".into()) {
println!("Pod already deleted");
} else {
println!("Deletion status: {:?}", status);
}
Ok(())
})
}
🚀 Running the Code
- Start your Kubernetes cluster.
- Run the code:
cargo run
🧪 Output Example
Listing pods in namespace default
- my-pod
- another-pod
When creating/deleting is enabled:
Creating pod test-pod
Pod test-pod created
Getting pod test-pod
Pod IP: Some("172.17.0.7")
Deleting pod test-pod
Deletion status: ObjectMeta { ... }
📌 Notes
- You can customize the containers, labels, etc., as needed.
- For production use, handle errors more robustly and add logging.
- You can extend this with Deployments, Services, CRDs, etc.
Would you like an example that watches for changes (like watch) or interacts with custom resources?