使用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解析xml中dom元素的方法
Mar 12 Python
10款最好的Web开发的 Python 框架
Mar 18 Python
使用Python编写一个简单的tic-tac-toe游戏的教程
Apr 16 Python
浅谈flask中的before_request与after_request
Jan 20 Python
python 列表,数组,矩阵两两转换tolist()的实例
Apr 04 Python
解决DataFrame排序sort的问题
Jun 07 Python
解决Python内层for循环如何break出外层的循环的问题
Jun 24 Python
Python如何通过Flask-Mail发送电子邮件
Jan 29 Python
Python 面向对象之类class和对象基本用法示例
Feb 02 Python
Pandas时间序列:时期(period)及其算术运算详解
Feb 25 Python
python3中celery异步框架简单使用+守护进程方式启动
Jan 20 Python
python爬虫scrapy基本使用超详细教程
Feb 20 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 反向排序和随机排序代码
2010/06/30 PHP
PHP面向对象概念
2011/11/06 PHP
如何判断php mysqli扩展类是否开启
2016/12/24 PHP
使用JS操作页面表格,元素的一些技巧
2007/02/02 Javascript
Div自动滚动到末尾的代码
2008/10/26 Javascript
去掉gridPanel表头全选框的小例子
2013/07/18 Javascript
jquery验证手机号码、邮箱格式是否正确示例代码
2013/07/28 Javascript
jQuery客户端分页实例代码
2013/11/18 Javascript
js实现简单div拖拽功能实例
2015/05/12 Javascript
jQuery插件实现表格隔行变色及鼠标滑过高亮显示效果代码
2016/02/25 Javascript
Javascript oop设计模式 面向对象编程简单实例介绍
2016/12/13 Javascript
Ajax 加载数据 练习代码
2017/01/05 Javascript
推荐15个最好用的JavaScript代码压缩工具
2019/02/13 Javascript
electron实现静默打印的示例代码
2019/08/12 Javascript
微信小程序实现滚动加载更多的代码
2019/12/06 Javascript
JavaScript实现指定数量的并发限制的示例代码
2020/03/10 Javascript
openlayers4.6.5实现距离量测和面积量测
2020/09/25 Javascript
如何通过JS实现日历简单算法
2020/10/14 Javascript
[00:57]英雄,你的补给到了!
2020/11/13 DOTA
详解Django中的权限和组以及消息
2015/07/23 Python
Python发送form-data请求及拼接form-data内容的方法
2016/03/05 Python
Python实现购物车功能的方法分析
2017/11/10 Python
python中正则表达式的使用方法
2018/02/25 Python
Python实现将json文件中向量写入Excel的方法
2018/03/26 Python
python 对txt中每行内容进行批量替换的方法
2018/07/11 Python
详解如何管理多个Python版本和虚拟环境
2019/05/10 Python
详解在Python中以绝对路径或者相对路径导入文件的方法
2019/08/30 Python
Python 代码调试技巧示例代码
2020/08/11 Python
网购亚洲时装、美容产品和生活百货:YesStyle
2016/09/15 全球购物
Boolean b = new Boolean(“abcde”); 会编译错误码
2013/11/27 面试题
方正Java笔试题
2014/07/03 面试题
欢送退休感言
2014/02/08 职场文书
薪酬专员岗位职责
2014/02/18 职场文书
安全施工责任书
2014/08/25 职场文书
合作合同协议书范本
2015/01/27 职场文书
python编程学习使用管道Pipe编写优化代码
2021/11/20 Python