合并kubeconfig配置文件和删除context脚本

需求

  • 需求一:
    当使用了kubectx之后,希望将所有的集群config都放在同一份配置文件中,方便切换。拿到一个新的集群(通常是一份kubeconfig)后,需要手动添加context、user、cluster字段。

kubecm 提供了配置文件合并的工具,但是合并之后会改掉context的名字,不太友好。

  • 需求二:
    当某个集群不再使用的时候,需要删除该context

合并脚本

直接用python处理

import yaml
import os
import time
from pathlib import Path

NEW_CONFIG_FILENAME = "config-all-new.yaml"


def read_kube_config(filename):
    with open(filename) as f:
        return yaml.full_load(f)


def output_kube_config(filename, config):
    with open(filename, "w") as f:
        f.write(config)
        print(f"导出配置文件【{filename}】成功")

def merge_kubeconfig(file_list):
    default_config = {
        "apiVersion": "v1",
        "kind": "Config",
        "preferences": {},
        "clusters": [],
        "contexts": [],
        "users": [],
        "current-context": "",
    }

    # 合并配置文件
    for file in file_list:
        config = read_kube_config(file)
        for cluster in config["clusters"]:
            default_config["clusters"].append(cluster)
        for user in config["users"]:
            default_config["users"].append(user)
        for context in config["contexts"]:
            default_config["contexts"].append(context)

    # 生成配置文件
    output_kube_config(NEW_CONFIG_FILENAME, yaml.dump(default_config, allow_unicode=True))

def remove_cluster_context(config_filepath, context_name):
    kube_config = read_kube_config(config_filepath)
    for context_idx, context in enumerate(kube_config["contexts"]):
        if context["name"] == context_name:
            # del cluster
            for cluster_idx, cluster in enumerate(kube_config["clusters"]):
                if cluster["name"] == context["context"]["cluster"]:
                    print(f'删除cluster【{cluster["name"]}】')
                    del kube_config["clusters"][cluster_idx]
            # del user
            for user_idx, user in enumerate(kube_config["users"]):
                if user["name"] == context["context"]["user"]:
                    print(f'删除user【{user["name"]}】')
                    del kube_config["users"][user_idx]
            # del context
            print(f'删除context【{context["name"]}】')
            del kube_config["contexts"][context_idx]

            # 备份配置
            current_date = time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime())
            os.system(f"cp ~/.kube/config ~/.kube/backup/config_backup_{current_date}_reason_del_context")
            output_kube_config(config_filepath, yaml.dump(kube_config, allow_unicode=True))

            return
    print(f"未找到context 【{context_name}】,删除失败")


def replace_default_kube_config():
    # 备份原配置
    current_date = time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime())

    print("备份旧配置...")
    os.system(f"cp ~/.kube/config ~/.kube/backup/config_backup_{current_date}_reason_merge_context")
    print("替换新配置...")
    os.system(f"cp ./{NEW_CONFIG_FILENAME} ~/.kube/config")
    print("删除配置文件...")
    os.system(f"rm -f ./{NEW_CONFIG_FILENAME}")
    os.system("unset KUBECONFIG")
    print("✅完成替换")


if __name__ == "__main__":
	# 合并kubeconfig
    # file_list = [
    #     f"{Path.home()}/.kube/config",
    #     f"{Path.home()}/.kube/config-new-cluster.yaml",
    # ]
    # merge_kubeconfig(file_list)
    #
    # replace_default_kube_config()
	
	# 删除context
    remove_cluster_context(f"{Path.home()}/.kube/config", "【本地测试环境】docker-desktop")
    pass

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值