SoFunction
Updated on 2024-12-19

Example of how to automatically generate K8S-YAML using python scripts

1. Generate

1.1, yaml to json

service template yaml

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

Structure of the converted json

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

1.2. Key Codes

# By passing in service_name and a list of ports
def create_service_yaml(service_name, ports):

 # Read the yaml into json and change all the ${jarName} that need to be changed.
 service_data['metadata']['name'] = service_name
 service_data['metadata']['labels']['name'] = service_name
 service_data['spec']['selector']['name'] = service_name

 # . More specifically, a dictionary list, difficult to modify directly due to the difficulty of determining the number of incoming ports
 # Create a new list, iterate through the list of incoming ports, generate a dictionary for each incoming port, add to the new list
 new_spec_ports = []
 for port in ports:
   port = int(port)
   new_port = {'port': port, 'targetPort': port}
   new_spec_ports.append(new_port)

 # Modify. to a new list
 service_data['spec']['ports'] = new_spec_ports

2. Generate

2.1, yaml to json

Deployment template 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: /library/${jarName}:${tag}
   imagePullSecrets:
    - name: registry-secret

Converted json structure

{
 "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": "/library/${jarName}:${tag}"
     }
    ],
    "imagePullSecrets": [
     {
      "name": "registry-secret"
     }
    ]
   }
  }
 }
}

2.2. Key Code

# Pass in service_name and image tag
def create_deploy_yaml(service_name, tag):

 # First modify all the ${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 

 # Due to the . specificity, we use direct modification
 # First splice the image field
 image = "/library/" + service_name + ":" + tag
 # Create a dictionary list of new_containers
 new_containers = [{'name': service_name, 'image': image}]
 deploy_data['spec']['template']['spec']['containers'] = new_containers

3. Complete scripts

#!/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  import YAML

yaml = YAML()

def create_service_yaml(service_name, ports):

  service_mould_file = "mould/"
  isServiceMould = (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_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:
      (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/"
  isDeployMould = (deploy_mould_file)

  if isDeployMould:
    with open(deploy_mould_file, encoding='utf-8') as yaml_obj:
      deploy_data = (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 = "/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:
      (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 = "\nPlease enter the tag to be generated: "
answer = input(prompt)
print("")

if (answer):
  raise SystemExit(answer + ': is Already exists!')
else:
  tag = answer
  (tag)
  for service_name, service_ports in ():
    create_service_yaml(service_name, service_ports)
    create_deploy_yaml(service_name, tag)

4. Implementation effects

➜ python3 Auto_Create_K8S_YAML.py

Please enter the name of the program you want to generatetag: 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

# Generated 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

# Generated 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: /library/info-message-service:0.0.1
   imagePullSecrets:
   - name: registry-secret

to this article on the use of python script to automatically generate K8S-YAML method example of the article is introduced to this, more relevant python automatically generate K8S-YAML content please search my previous posts or continue to browse the following related articles I hope that you will support me in the future more!