diff --git a/src/Traits/Cluster/LoadsFromKubeConfig.php b/src/Traits/Cluster/LoadsFromKubeConfig.php index 000c72af..406d20be 100644 --- a/src/Traits/Cluster/LoadsFromKubeConfig.php +++ b/src/Traits/Cluster/LoadsFromKubeConfig.php @@ -6,6 +6,7 @@ use RenokiCo\PhpK8s\Exceptions\KubeConfigClusterNotFound; use RenokiCo\PhpK8s\Exceptions\KubeConfigContextNotFound; use RenokiCo\PhpK8s\Exceptions\KubeConfigUserNotFound; +use RenokiCo\PhpK8s\Kinds\K8sResource; trait LoadsFromKubeConfig { @@ -70,7 +71,7 @@ public function fromKubeConfigYamlFile(string $path = '/.kube/config', string $c */ protected function loadKubeConfigFromArray(array $kubeconfig, string $context): void { - $contextConfig = collect($kubeconfig['contexts'] ?? [])->where('name', $context)->first(); + $contextConfig = collect($kubeconfig['contexts'] ?? [])->firstWhere('name', $context); if (! $contextConfig) { throw new KubeConfigContextNotFound("The context {$context} does not exist in the provided Kube Config file."); @@ -78,6 +79,10 @@ protected function loadKubeConfigFromArray(array $kubeconfig, string $context): ['context' => ['cluster' => $cluster, 'user' => $user]] = $contextConfig; + if (isset($contextConfig['context']['namespace'])) { + K8sResource::setDefaultNamespace($contextConfig['context']['namespace']); + } + if (! $clusterConfig = collect($kubeconfig['clusters'] ?? [])->where('name', $cluster)->first()) { throw new KubeConfigClusterNotFound("The cluster {$cluster} does not exist in the provided Kube Config file."); } diff --git a/tests/cluster/kubeconfig.yaml b/tests/cluster/kubeconfig.yaml index 39a2314b..df90f1e0 100644 --- a/tests/cluster/kubeconfig.yaml +++ b/tests/cluster/kubeconfig.yaml @@ -13,18 +13,22 @@ contexts: cluster: minikube user: minikube name: minikube + namespace: some-namespace - context: cluster: minikube-2 user: minikube-2 name: minikube-2 + namespace: some-namespace - context: cluster: no-cluster user: minikube name: minikube-without-cluster + namespace: some-namespace - context: cluster: minikube user: no-user name: minikube-without-user + namespace: some-namespace current-context: minikube kind: Config preferences: {}