Skip to content

Instantly share code, notes, and snippets.

@jmarhee
Created April 9, 2023 05:20
Show Gist options
  • Save jmarhee/b306e618c3f8338fba930ed0c5736009 to your computer and use it in GitHub Desktop.
Save jmarhee/b306e618c3f8338fba930ed0c5736009 to your computer and use it in GitHub Desktop.
Delete all Kubernetes Pods in a specific namespace older than a user-specified number of hours. (i.e. all Pods in namespace "app-time-limited" older than 1 hour)
[dependencies]
kube = "0.64.0"
k8s-openapi = "0.12.0"
use std::env;
use std::time::{Duration, SystemTime};
use k8s_openapi::api::core::v1::{Pod, PodList};
use k8s_openapi::apimachinery::pkg::apis::meta::v1::Time;
use kube::{
api::{Api, ListParams},
Client,
};
fn main() -> anyhow::Result<()> {
let namespace = env::var("NAMESPACE")?;
let age_limit_hours = env::var("AGE_LIMIT_HOURS")?.parse::<u64>()?;
let age_limit = SystemTime::now() - Duration::from_secs(age_limit_hours * 3600);
let kubeconfig = kube::Config::infer().await?;
let client = Client::new(kubeconfig);
let pods: Api<Pod> = Api::namespaced(client, &namespace);
let params = ListParams::default()
.labels("app=myapp") // Replace with your own label selector
.timeout(10); // Set a timeout to avoid hanging indefinitely
let pod_list: PodList = pods.list(&params).await?;
for pod in pod_list.items {
let start_time = match pod.status.container_statuses {
Some(ref statuses) if !statuses.is_empty() => statuses[0].state.as_ref().and_then(|state| state.running.as_ref()).map(|running| &running.started_at),
_ => None,
};
if let Some(start_time) = start_time {
let started = start_time.parse::<Time>()?.into();
if started < age_limit {
println!("Deleting Pod {} in namespace {}", pod.metadata.name, namespace);
pods.delete(&pod.metadata.name, &Default::default()).await?;
}
}
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment