From f423e3ddda76f89035f1e2937523d0f1d9ddadfc Mon Sep 17 00:00:00 2001 From: weibaohui Date: Tue, 21 Nov 2023 14:15:18 +0800 Subject: [PATCH] kubeconfig change --- src/backend/k8s/client/client.service.ts | 37 ++++++++---------------- 1 file changed, 12 insertions(+), 25 deletions(-) diff --git a/src/backend/k8s/client/client.service.ts b/src/backend/k8s/client/client.service.ts index 1e21299..5c8f7d2 100644 --- a/src/backend/k8s/client/client.service.ts +++ b/src/backend/k8s/client/client.service.ts @@ -1,7 +1,6 @@ import os from 'node:os' import process from 'node:process' import fs from 'node:fs' -import path from 'node:path' import { KubeConfig } from '@backend/model/KubeConfig' import { KubernetesObject } from '@kubernetes/client-node' import * as k8s from '@kubernetes/client-node' @@ -13,27 +12,7 @@ import YAML from 'yaml' export class ClientService { private readonly logger = new Logger(ClientService.name) private kc = new k8s.KubeConfig() - private kubeConfigList: Map = new Map() - public autoLoadKubeConfig() { - const defaultHome = process.env.HOME || process.env.USERPROFILE - const folderPath = `${defaultHome}/.kube` - const items = fs.readdirSync(folderPath) - items.forEach((item) => { - const itemPath = path.join(folderPath, item) - const stats = fs.statSync(itemPath) - if (stats.isFile()) { - const data = fs.readFileSync(`${folderPath}/${item}`, 'utf8') - const x: KubeConfig = YAML.parse(data) - const key = x['current-context'] - this.kubeConfigList.set(key, data) - } - }) - } - - public getKubeConfigByContext(key: string) { - this.autoLoadKubeConfig() - this.kc.loadFromString(this.kubeConfigList.get(key)) - } + private configPath = `${process.env.HOME || process.env.USERPROFILE}/.kube/config` public getKubeConfig() { if (process.env.inCluster) { @@ -41,8 +20,7 @@ export class ClientService { return this.kc } - const home = process.env.HOME || process.env.USERPROFILE - this.kc.loadFromFile(`${home}/.kube/config`) + this.kc.loadFromFile(this.configPath) return this.kc } @@ -55,7 +33,16 @@ export class ClientService { } public setContext(name) { - this.getKubeConfig().setCurrentContext(name) + if (process.env.inCluster) { + this.logger.error(`inCluster change context to ${name} error`) + return + } + const data = fs.readFileSync(this.configPath, 'utf8') + const x: KubeConfig = YAML.parse(data) + // const key = x['current-context'] + x['current-context'] = name + const s = YAML.stringify(x) + fs.writeFileSync(this.configPath, s) } public getAppsV1Api() {