Rust has a kubernetes client crate which allows us to write code against Kubernetes via the client (i.e. instead of calling out to kubectl itself).
Create yourself a binary Rust application with the following dependencies
[dependencies]
k8s-openapi = { version = "0.26.0", default-features = false, features = ["v1_32"] }
kube = { version = "2.0.1", features = ["runtime", "client"] }
tokio = { version = "1.30", features = ["full"] }
anyhow = "1.0"
Note: Check the k8s-openapi features match you installed kubernetes, run kubectl version to check your server version and use this.
This is very much a starter post, so I’m going to just change main.rs to simply instantiate a client and get all pods running across all namespaces
use kube::{Api, Client};
use k8s_openapi::api::core::v1::Pod;
use kube::runtime::reflector::Lookup;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let client = Client::try_default().await?;
let pods: Api<Pod> = Api::all(client);
let pod_list = pods.list(&Default::default()).await?;
for p in pod_list {
println!("Pod name: {:?}", p.name().expect("Pod name missing"));
}
Ok(())
}
If you want to use the default namespace then change the line
let pods: Api<Pod> = Api::all(client);
to
let pods: Api<Pod> = Api::default_namespaced(client);
or if you want to get pods from a specific namespace use
let pods: Api<Pod> = Api::namespaced(client, "mynamespace");
Note: Ofcourse you could use “default” for the default namespace or “” for all namespaces in place of “mynamespace”.
Code
Code is available on GitHub.