使用python脚本自动生成K8S-YAML的方法示例


Posted in Python onJuly 12, 2020

1、生成 servie.yaml

1.1、yaml转json

service模板yaml

apiVersion: v1
kind: Service
metadata:
 name: ${jarName}
 labels:
  name: ${jarName}
  version: v1
spec:
 ports:
  - port: ${port}
   targetPort: ${port}
 selector:
  name: ${jarName}

转成json的结构

{
 "apiVersion": "v1",
 "kind": "Service",
 "metadata": {
  "name": "${jarName}",
  "labels": {
   "name": "${jarName}",
   "version": "v1"
  }
 },
 "spec": {
  "ports": [
   {
    "port": "${port}",
    "targetPort": "${port}"
   }
  ],
  "selector": {
   "name": "${jarName}"
  }
 }
}

1.2、关键代码

# 通过传入service_name及ports列表
def create_service_yaml(service_name, ports):

 # 将yaml读取为json,然后修改所有需要修改的${jarName}
 service_data['metadata']['name'] = service_name
 service_data['metadata']['labels']['name'] = service_name
 service_data['spec']['selector']['name'] = service_name

 # .spec.ports 比较特殊,是一个字典列表,由于传入的ports难以确定数量,难以直接修改
 # 新建一个列表,遍历传入的ports列表,将传入的每个port都生成为一个字典,添加入新列表中
 new_spec_ports = []
 for port in ports:
   port = int(port)
   new_port = {'port': port, 'targetPort': port}
   new_spec_ports.append(new_port)

 # 修改.spec.ports为新列表
 service_data['spec']['ports'] = new_spec_ports

2、生成 deployment.yaml

2.1、yaml转json

deployment模板yaml

apiVersion: apps/v1
kind: Deployment
metadata:
 name: ${jarName}
 labels:
  name: ${jarName}
spec:
 selector:
  matchLabels:
   name: ${jarName}
 replicas: 1
 template:
  metadata:
   labels:
    name: ${jarName}
  spec:
   containers:
   - name: ${jarName}
    image: reg.test.local/library/${jarName}:${tag}
   imagePullSecrets:
    - name: registry-secret

转成的json结构

{
 "apiVersion": "apps/v1",
 "kind": "Deployment",
 "metadata": {
  "name": "${jarName}",
  "labels": {
   "name": "${jarName}"
  }
 },
 "spec": {
  "selector": {
   "matchLabels": {
    "name": "${jarName}"
   }
  },
  "replicas": 1,
  "template": {
   "metadata": {
    "labels": {
     "name": "${jarName}"
    }
   },
   "spec": {
    "containers": [
     {
      "name": "${jarName}",
      "image": "reg.test.local/library/${jarName}:${tag}"
     }
    ],
    "imagePullSecrets": [
     {
      "name": "registry-secret"
     }
    ]
   }
  }
 }
}

2.2、关键代码

# 传入service_name及image tag
def create_deploy_yaml(service_name, tag):

 # 首先修改所有的${jarName}
 deploy_data['metadata']['name'] = service_name
 deploy_data['metadata']['labels']['name'] = service_name
 deploy_data['spec']['selector']['matchLabels']['name'] = service_name
 deploy_data['spec']['template']['metadata']['labels']['name'] = service_name 

 # 由于.spec.template.spec.containers的特殊性,我们采用直接修改的方式
 # 首先拼接image字段
 image = "reg.test.local/library/" + service_name + ":" + tag
 # 创建new_containers字典列表
 new_containers = [{'name': service_name, 'image': image}]
 deploy_data['spec']['template']['spec']['containers'] = new_containers

3、完整脚本

#!/usr/bin/python
# encoding: utf-8

"""
The Script for Auto Create Deployment Yaml.

File:        auto_create_deploy_yaml
User:        miaocunfa
Create Date:    2020-06-10
Create Time:    17:06
"""

import os
from ruamel.yaml import YAML

yaml = YAML()

def create_service_yaml(service_name, ports):

  service_mould_file = "mould/info-service-mould.yaml"
  isServiceMould = os.path.isfile(service_mould_file)

  if isServiceMould:
    # read Service-mould yaml convert json
    with open(service_mould_file, encoding='utf-8') as yaml_obj:
      service_data = yaml.load(yaml_obj)

    # Update jarName
    service_data['metadata']['name'] = service_name
    service_data['metadata']['labels']['name'] = service_name
    service_data['spec']['selector']['name'] = service_name

    # Update port
    new_spec_ports = []
    for port in ports:
      port = int(port)
      portname = 'port' + str(port)
      new_port = {'name': portname, 'port': port, 'targetPort': port}
      new_spec_ports.append(new_port)
    service_data['spec']['ports'] = new_spec_ports

    # json To service yaml
    save_file = tag + '/' + service_name + '_svc.yaml'
    with open(save_file, mode='w', encoding='utf-8') as yaml_obj:
      yaml.dump(service_data, yaml_obj)

    print(save_file + ": Success!")
  else:
    print("Service Mould File is Not Exist!")

def create_deploy_yaml(service_name, tag):

  deploy_mould_file = "mould/info-deploy-mould.yaml"
  isDeployMould = os.path.isfile(deploy_mould_file)

  if isDeployMould:
    with open(deploy_mould_file, encoding='utf-8') as yaml_obj:
      deploy_data = yaml.load(yaml_obj)

    # Update jarName
    deploy_data['metadata']['name'] = service_name
    deploy_data['metadata']['labels']['name'] = service_name
    deploy_data['spec']['selector']['matchLabels']['name'] = service_name
    deploy_data['spec']['template']['metadata']['labels']['name'] = service_name 

    # Update containers
    image = "reg.test.local/library/" + service_name + ":" + tag
    new_containers = [{'name': service_name, 'image': image}]
    deploy_data['spec']['template']['spec']['containers'] = new_containers

    # json To service yaml
    save_file = tag + '/' + service_name + '_deploy.yaml'
    with open(save_file, mode='w', encoding='utf-8') as yaml_obj:
      yaml.dump(deploy_data, yaml_obj)

    print(save_file + ": Success!")
  else:
    print("Deploy Mould File is Not Exist!")

services = {
  'info-gateway':        ['9999'],
  'info-admin':         ['7777'],
  'info-config':        ['8888'],
  'info-message-service':    ['8555', '9666'],
  'info-auth-service':     ['8666'],
  'info-scheduler-service':   ['8777'],
  'info-uc-service':      ['8800'],
  'info-ad-service':      ['8801'],
  'info-community-service':   ['8802'],
  'info-groupon-service':    ['8803'],
  'info-hotel-service':     ['8804'],
  'info-nearby-service':    ['8805'],
  'info-news-service':     ['8806'],
  'info-store-service':     ['8807'],
  'info-payment-service':    ['8808'],
  'info-agent-service':     ['8809'],
  'info-consumer-service':   ['8090'],
}

prompt = "\n请输入要生成的tag: "
answer = input(prompt)
print("")

if os.path.isdir(answer):
  raise SystemExit(answer + ': is Already exists!')
else:
  tag = answer
  os.makedirs(tag)
  for service_name, service_ports in services.items():
    create_service_yaml(service_name, service_ports)
    create_deploy_yaml(service_name, tag)

4、执行效果

➜ python3 Auto_Create_K8S_YAML.py

请输入要生成的tag: 0.0.1

0.0.1/info-gateway_svc.yaml: Success!
0.0.1/info-gateway_deploy.yaml: Success!
0.0.1/info-admin_svc.yaml: Success!
0.0.1/info-admin_deploy.yaml: Success!
0.0.1/info-config_svc.yaml: Success!
0.0.1/info-config_deploy.yaml: Success!
0.0.1/info-message-service_svc.yaml: Success!
0.0.1/info-message-service_deploy.yaml: Success!
0.0.1/info-auth-service_svc.yaml: Success!
0.0.1/info-auth-service_deploy.yaml: Success!
0.0.1/info-scheduler-service_svc.yaml: Success!
0.0.1/info-scheduler-service_deploy.yaml: Success!
0.0.1/info-uc-service_svc.yaml: Success!
0.0.1/info-uc-service_deploy.yaml: Success!
0.0.1/info-ad-service_svc.yaml: Success!
0.0.1/info-ad-service_deploy.yaml: Success!
0.0.1/info-community-service_svc.yaml: Success!
0.0.1/info-community-service_deploy.yaml: Success!
0.0.1/info-groupon-service_svc.yaml: Success!
0.0.1/info-groupon-service_deploy.yaml: Success!
0.0.1/info-hotel-service_svc.yaml: Success!
0.0.1/info-hotel-service_deploy.yaml: Success!
0.0.1/info-nearby-service_svc.yaml: Success!
0.0.1/info-nearby-service_deploy.yaml: Success!
0.0.1/info-news-service_svc.yaml: Success!
0.0.1/info-news-service_deploy.yaml: Success!
0.0.1/info-store-service_svc.yaml: Success!
0.0.1/info-store-service_deploy.yaml: Success!
0.0.1/info-payment-service_svc.yaml: Success!
0.0.1/info-payment-service_deploy.yaml: Success!
0.0.1/info-agent-service_svc.yaml: Success!
0.0.1/info-agent-service_deploy.yaml: Success!
0.0.1/info-consumer-service_svc.yaml: Success!
0.0.1/info-consumer-service_deploy.yaml: Success!

➜ ll
total 12
drwxr-xr-x. 2 root root 4096 Jun 29 18:24 0.0.1

# 生成的 service yaml
➜ cat info-message-service_svc.yaml
apiVersion: v1
kind: Service
metadata:
 name: info-message-service
 labels:
  name: info-message-service
  version: v1
spec:
 ports:
 - name: port8555
  port: 8555
  targetPort: 8555
 - name: port9666
  port: 9666
  targetPort: 9666
 selector:
  name: info-message-service

# 生成的 deployment yaml
➜ cat info-message-service_deploy.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
 name: info-message-service
 labels:
  name: info-message-service
spec:
 selector:
  matchLabels:
   name: info-message-service
 replicas: 2
 template:
  metadata:
   labels:
    name: info-message-service
  spec:
   containers:
   - name: info-message-service
    image: reg.test.local/library/info-message-service:0.0.1
   imagePullSecrets:
   - name: registry-secret

到此这篇关于使用python脚本自动生成K8S-YAML的方法示例的文章就介绍到这了,更多相关python自动生成K8S-YAML内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python实现抓取页面上链接的简单爬虫分享
Jan 21 Python
numpy.delete删除一列或多列的方法
Apr 03 Python
Django实现微信小程序的登录验证功能并维护登录态
Jul 04 Python
Python3+PyInstall+Sciter解决报错缺少dll、html等文件问题
Jul 15 Python
Python 异常处理Ⅳ过程图解
Oct 18 Python
python 类之间的参数传递方式
Dec 20 Python
python给图像加上mask,并提取mask区域实例
Jan 19 Python
使用Python合成图片的实现代码(图片添加个性化文本,图片上叠加其他图片)
Apr 30 Python
python中np是做什么的
Jul 21 Python
详解如何在PyCharm控制台中输出彩色文字和背景
Aug 17 Python
python实现简单遗传算法
Sep 18 Python
python给list排序的简单方法
Dec 10 Python
python读取excel进行遍历/xlrd模块操作
Jul 12 #Python
django rest framework 自定义返回方式
Jul 12 #Python
Django+RestFramework API接口及接口文档并返回json数据操作
Jul 12 #Python
Python3交互式shell ipython3安装及使用详解
Jul 11 #Python
Python QTimer实现多线程及QSS应用过程解析
Jul 11 #Python
面向新手解析python Beautiful Soup基本用法
Jul 11 #Python
基于python实现判断字符串是否数字算法
Jul 10 #Python
You might like
小偷PHP+Html+缓存
2006/11/25 PHP
setcookie中Cannot modify header information-headers already sent by错误的解决方法详解
2013/05/08 PHP
PHP模糊查询的实现方法(推荐)
2016/09/06 PHP
在Z-Blog中运行代码[html][/html](纯JS版)
2007/03/25 Javascript
fckeditor 获取文本框值的实现代码
2009/02/09 Javascript
基于jquery的cookie的用法
2011/01/10 Javascript
Javascript算符的优先级介绍
2013/03/20 Javascript
jQuery 如何先创建、再修改、后添加DOM元素
2014/05/20 Javascript
JS中setTimeout的巧妙用法前端函数节流
2016/03/24 Javascript
JS中跨页面调用变量和函数的方法(例如a.js 和 b.js中互相调用)
2016/11/01 Javascript
详解Vue.js 2.0 如何使用axios
2017/04/21 Javascript
Vue2.0如何发布项目实战
2017/07/27 Javascript
vue移动端屏幕适配详解
2019/04/30 Javascript
vue自定义switch开关组件,实现样式可自行更改
2019/11/01 Javascript
浅谈JavaScript节流和防抖函数
2020/08/25 Javascript
[01:33:25]DOTA2-DPC中国联赛 正赛 Elephant vs IG BO3 第一场 1月24日
2021/03/11 DOTA
python求列表交集的方法汇总
2014/11/10 Python
一些常用的Python爬虫技巧汇总
2016/09/28 Python
Python动刷新抢12306火车票的代码(附源码)
2018/01/24 Python
Python实现读取字符串按列分配后按行输出示例
2018/04/17 Python
解决pandas .to_excel不覆盖已有sheet的问题
2018/12/10 Python
基于Python实现拆分和合并GIF动态图
2019/10/22 Python
用Python做一个久坐提醒小助手的示例代码
2020/02/10 Python
在python中利用dict转json按输入顺序输出内容方式
2020/02/27 Python
解决Keras的自定义lambda层去reshape张量时model保存出错问题
2020/07/01 Python
Django如何批量创建Model
2020/09/01 Python
CSS的background属性及CSS3的背景图片设置总结
2016/06/13 HTML / CSS
加工操作管理制度
2014/01/19 职场文书
大班幼儿评语大全
2014/04/30 职场文书
计划生育证明格式范本
2014/09/12 职场文书
会计求职自荐信
2015/03/26 职场文书
2015年机关后勤工作总结
2015/05/26 职场文书
《桂花雨》教学反思
2016/02/19 职场文书
Python破解极验滑动验证码详细步骤
2021/05/21 Python
用php如何解决大文件分片上传问题
2021/07/07 PHP
CSS子盒子水平和垂直居中的五种方法
2022/07/23 HTML / CSS