Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create kubernetes yaml file using pure python

Actually, i have kubernetes cluster set up. I want to generate yaml config file dynamically based on a template using python.

template.yaml

apiVersion: v1
kind: pod
metadata:
  name: $name
spec:
  replicas: $replicas
  template:
    metadata:
      labels:
        run: $name
    spec:
      containers:
      - name: $name
        image: $image
        ports:
        - containerPort: 80

Placeholders name, replicas and image are the input of my python method. Any help will be appreciated.

like image 562
DiStephane Avatar asked Aug 27 '26 03:08

DiStephane


1 Answers

If you want a way to do it using pure python, with no libraries, here's one using multiline strings and format:

def writeConfig(**kwargs):
    template = """
    apiVersion: v1
    kind: pod
    metadata:
      name: {name}
    spec:
      replicas: {replicas}
      template:
        metadata:
          labels:
            run: {name}
        spec:
          containers:
          - name: {name}
            image: {image}
            ports:
            - containerPort: 80"""

    with open('somefile.yaml', 'w') as yfile:
        yfile.write(template.format(**kwargs))

# usage:
writeConfig(name="someName", image="myImg", replicas="many")
like image 174
Filip Haglund Avatar answered Aug 29 '26 17:08

Filip Haglund



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!