Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions src/config/kube_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,32 @@ pub struct KubeConfigLoader {
}

impl KubeConfigLoader {
pub fn load<P: AsRef<Path>>(path: P) -> Result<KubeConfigLoader, Error> {
pub fn load<P: AsRef<Path>>(
path: P,
context: Option<String>,
cluster: Option<String>,
user: Option<String>,
) -> Result<KubeConfigLoader, Error> {
let config = Config::load_config(path)?;
let context_name = context.as_ref().unwrap_or(&config.current_context);
let current_context = config
.contexts
.iter()
.find(|named_context| named_context.name == config.current_context)
.find(|named_context| &named_context.name == context_name)
.map(|named_context| &named_context.context)
.ok_or(format_err!("Unable to load current context"))?;
let cluster_name = cluster.as_ref().unwrap_or(&current_context.cluster);
let cluster = config
.clusters
.iter()
.find(|named_cluster| named_cluster.name == current_context.cluster)
.find(|named_cluster| &named_cluster.name == cluster_name)
.map(|named_cluster| &named_cluster.cluster)
.ok_or(format_err!("Unable to load cluster of current context"))?;
let user_name = user.as_ref().unwrap_or(&current_context.user);
let user = config
.auth_infos
.iter()
.find(|named_user| named_user.name == current_context.user)
.find(|named_user| &named_user.name == user_name)
.map(|named_user| {
let mut user = named_user.auth_info.clone();
match user.load_gcp() {
Expand Down
24 changes: 23 additions & 1 deletion src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,33 @@ impl Configuration {
/// .expect("failed to load kubeconfig");
/// ```
pub fn load_kube_config() -> Result<Configuration, Error> {
load_kube_config_with(Default::default())
}

/// ConfigOptions stores options used when loading kubeconfig file.
#[derive(Default)]
pub struct ConfigOptions {
pub context: Option<String>,
pub cluster: Option<String>,
pub user: Option<String>,
}

/// Returns a config includes authentication and cluster information from kubeconfig file.
///
/// # Example
/// ```no_run
/// use kubernetes::config;
///
/// let kubeconfig = config::load_kube_config()
/// .expect("failed to load kubeconfig");
/// ```
pub fn load_kube_config_with(options: ConfigOptions) -> Result<Configuration, Error> {
let kubeconfig = utils::kubeconfig_path()
.or_else(utils::default_kube_path)
.ok_or(format_err!("Unable to load kubeconfig"))?;

let loader = KubeConfigLoader::load(kubeconfig)?;
let loader =
KubeConfigLoader::load(kubeconfig, options.context, options.cluster, options.user)?;
let token = match &loader.user.token {
Some(token) => Some(token.clone()),
None => {
Expand Down