python使用toml模块生成containerd仓库配置

  • 2025-03-27 19:35:36
  • 脚本
  • 40
  • shevechco

之前手工配置过contianerd的仓库,配置有些繁琐,具体可以查看这个笔记,现在写了个脚本去修改,脚本内容如下:

#!/usr/bin/python3
#coding: utf-8
import toml
import sys
import os
import time
import shutil
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(filename)s[line:%(lineno)d] %(message)s', datefmt='%Y-%m-%d')
config_path = r"/etc/containerd/"
config_name = "config.toml"
mirrors = "192.168.1.2"
username = ""
password = ""


def modify_config(config, mirrors, username, password):
	config["plugins"]["io.containerd.grpc.v1.cri"]["registry"]["mirrors"][mirrors] = {
		"endpoint": ["http://{}".format(mirrors)]
	}
	if username:
		config["plugins"]["io.containerd.grpc.v1.cri"]["registry"]["configs"][mirrors]["tls"] = {
			"insecure_skip_verify": True
		}
		config["plugins"]["io.containerd.grpc.v1.cri"]["registry"]["configs"][mirrors]["auth"] = {
			"username": username,
			"password": password
		}
	return config

if __name__ == "__main__":
	if not os.path.exists(os.path.join(config_path, config_name)):
		sys.exit("不能找到container配置文件 {}".format(os.path.join(config_path, config_name)))

	try:
		with open(os.path.join(config_path, config_name), "r") as f:
			config = toml.load(f)
			logging.debug("打印当前config配置: {}".format(config))
			new_config = modify_config(config)
			logging.debug("打印修改后的config配置: {}".format(new_config))
	except Exception as e:
		sys.exit("修改container配置文件失败, {}".format(e))

	logging.info("containerd配置修改完成, 开始备份{}文件...".format(config_name))
	shutil.copyfile(os.path.join(config_path, config_name), os.path.join(config_path, config_name+"_"+time.strftime("%Y%m%d%H%M%S", time.localtime())))
	logging.info("将修改后的container配置写回 {} 文件".format(config_name))
	try:
		with open(os.path.join(config_path, config_name), "w") as f:
			toml.dump(config, f)
	except Exception as e:
		sys.exit("写回containerd配置失败, {}".format(e))

	logging.info("修改containerd配置操作完成!!!")

顶部的的一些配置可以根据自己情况进行手工修改,如果还需要手工配置,可以查看我之前的笔记:https://sulao.cn/post/952

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.sulao.cn/post/1009

相关推荐