DiStephane
DiStephane

Reputation: 105

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.

Upvotes: 3

Views: 4014

Answers (2)

Drathier
Drathier

Reputation: 14539

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")

Upvotes: 9

senden9
senden9

Reputation: 336

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)

Upvotes: 1

Related Questions