使用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 07 Python
python版本的读写锁操作方法
Apr 25 Python
Django 2.0版本的新特性抢先看!
Jan 05 Python
python3 遍历删除特定后缀名文件的方法
Apr 23 Python
python numpy 部分排序 寻找最大的前几个数的方法
Jun 27 Python
对Python闭包与延迟绑定的方法详解
Jan 07 Python
python flask解析json数据不完整的解决方法
May 26 Python
tesserocr与pytesseract模块的使用方法解析
Aug 30 Python
Python制作简易版小工具之计算天数的实现思路
Feb 13 Python
Python pip install之SSL异常处理操作
Sep 03 Python
Python虚拟环境的创建和使用详解
Sep 07 Python
详解numpy.ndarray.reshape()函数的参数问题
Oct 13 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
Win2003服务器安全加固设置--进一步提高服务器安全性
2007/05/23 PHP
解析阿里云ubuntu12.04环境下配置Apache+PHP+PHPmyadmin+MYsql
2013/06/26 PHP
如何在php中正确的使用json
2013/08/06 PHP
PHP goto语句简介和使用实例
2014/03/11 PHP
PHP中使用asort进行中文排序失效的问题处理
2014/08/18 PHP
Zend Framework实现将session存储在memcache中的方法
2016/03/22 PHP
Zend Framework实现多服务器共享SESSION数据的方法
2016/03/22 PHP
今天你说520了吗?不仅有php表白书还有java表白神器
2016/05/20 PHP
php curl发送请求实例方法
2019/08/01 PHP
PHP实现简单日历类编写
2020/08/28 PHP
JavaScript使用IEEE 标准进行二进制浮点运算产生莫名错误的解决方法
2011/05/28 Javascript
字符串的replace方法应用浅析
2011/12/06 Javascript
JS实现多物体缓冲运动实例代码
2013/11/29 Javascript
Javascript selection的兼容性写法介绍
2013/12/20 Javascript
3种Jquery限制文本框只能输入数字字母的方法
2014/12/03 Javascript
JQuery的ON()方法支持的所有事件罗列
2015/02/28 Javascript
JS判断字符串包含的方法
2015/05/05 Javascript
javascript实现数组中的内容随机输出
2015/08/11 Javascript
Vue + Webpack + Vue-loader学习教程之相关配置篇
2017/03/14 Javascript
浅要分析Python程序与C程序的结合使用
2015/04/07 Python
Python面向对象之继承代码详解
2018/01/29 Python
Python及Django框架生成二维码的方法分析
2018/01/31 Python
Python 绘图库 Matplotlib 入门教程
2018/04/19 Python
Linux安装Python3如何和系统自带的Python2并存
2020/07/23 Python
文秘专业自荐信
2013/10/14 职场文书
高三高考决心书
2014/03/11 职场文书
文明生主要事迹
2014/05/25 职场文书
深入开展党的群众路线教育实践活动心得体会
2014/11/05 职场文书
2015年医药代表工作总结
2015/04/25 职场文书
校园安全教育心得体会
2016/01/15 职场文书
实习报告怎么写
2019/06/20 职场文书
创业计划书之川味火锅店
2019/09/02 职场文书
《刺客之王:C罗全景传记》:时代从来不会亏待手艺人
2019/11/28 职场文书
Nginx配置https原理及实现过程详解
2021/03/31 Servers
解决Swagger2返回map复杂结构不能解析的问题
2021/07/02 Java/Android
CentOS7设置ssh服务以及端口修改方式
2022/12/24 Servers