mz_orchestrator_kubernetes/util.rs
1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use anyhow::bail;
11use kube::config::KubeConfigOptions;
12use kube::{Client, Config};
13
14/// Constructs a new Kubernetes client.
15///
16/// The `context` specifies the Kubernetes context to load. If loading from the
17/// context fails, the in-cluster configuration is attempted.
18///
19/// Returns the constructed client and the default namespace loaded from the
20/// configuration.
21pub async fn create_client(context: String) -> Result<(Client, String), anyhow::Error> {
22 let kubeconfig_options = KubeConfigOptions {
23 context: Some(context),
24 ..Default::default()
25 };
26 let kubeconfig = match Config::from_kubeconfig(&kubeconfig_options).await {
27 Ok(config) => config,
28 Err(kubeconfig_err) => match Config::incluster_env() {
29 Ok(config) => config,
30 Err(in_cluster_err) => {
31 bail!(
32 "failed to infer config: in-cluster: ({in_cluster_err}), kubeconfig: ({kubeconfig_err})"
33 );
34 }
35 },
36 };
37 let namespace = kubeconfig.default_namespace.clone();
38 let client = Client::try_from(kubeconfig)?;
39 Ok((client, namespace))
40}