Skip to content

Instantly share code, notes, and snippets.

@jeeger
Created January 10, 2023 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeeger/cb06efae517826f157617a444f06143b to your computer and use it in GitHub Desktop.
Save jeeger/cb06efae517826f157617a444f06143b to your computer and use it in GitHub Desktop.
Print current kubernetes context or '?'
use anyhow::{Error, Result};
use std::env;
use std::fs::read_to_string;
use std::io::{stderr, stdout, Write};
use yaml_rust::YamlLoader;
fn kube_config_path() -> String {
let mut home = dirs::home_dir().expect("No home directory found");
home.extend(vec![".kube", "config"]);
env::var("KUBECONFIG").unwrap_or(
home.into_os_string()
.into_string()
.expect("Could not convert home path"),
)
}
fn current_context(cfgpath: &str) -> Result<String> {
let string = read_to_string(cfgpath)?;
let yaml = YamlLoader::load_from_str(&string)?;
if yaml.len() == 0 {
return Err(Error::msg(format!("No YAML in {}", cfgpath)));
}
let context = yaml[0]["current-context"].as_str();
context
.map(|str| String::from(str))
.ok_or(Error::msg(format!(
"No current context found in config file {}",
cfgpath
)))
}
fn main() {
let config_path = kube_config_path();
match current_context(&config_path) {
Ok(ctx) => {
let _ = stdout().write_all(ctx.as_bytes());
std::process::exit(0);
}
Err(e) => {
let _ = stderr().write_all(e.to_string().as_bytes());
let _ = stdout().write_all("?".as_bytes());
std::process::exit(0);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment