Skip to content

Commit

Permalink
kubeconfig change
Browse files Browse the repository at this point in the history
  • Loading branch information
weibaohui committed Nov 21, 2023
1 parent 7cb3c34 commit f423e3d
Showing 1 changed file with 12 additions and 25 deletions.
37 changes: 12 additions & 25 deletions src/backend/k8s/client/client.service.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -13,36 +12,15 @@ import YAML from 'yaml'
export class ClientService {
private readonly logger = new Logger(ClientService.name)
private kc = new k8s.KubeConfig()
private kubeConfigList: Map<string, string> = new Map<string, string>()
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) {
this.kc.loadFromCluster()
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
}

Expand All @@ -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() {
Expand Down

0 comments on commit f423e3d

Please sign in to comment.