DiStephane DiStephane - 6 months ago 59
Python Question

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.

Answer

If you want to work only with templates, pure python and if your variables are already checked (safe) than you can use the format method of strings.

Here is a example:

# load your template from somewhere
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
"""
# insert your values
specific_yaml = template.format(name="test_name", image="test.img", replicas="False")
print(specific_yaml)