Search code examples
python-3.xjinja2

How to use data file for jinja2 template


I'm creating a python3 jinja2 script that receives as parameters two files:

  1. The template file called depl.yaml.j2
  2. The data file called data.dev

The script is supposed to output a k8s file. ps. I removed the argparse part of the script to keep it simple. The contents of the file called called depl.yaml.j2 is:

...
    spec:
      restartPolicy: Always
      hostAliases:
{% for p in hostAliases %}
{% set IP = p["IP"] %}
{% set HOSTNAME = p["HOSTNAME"] %}
      - ip: "{{ IP }}"
        hostnames:
        - "{{ HOSTNAME }}"
{% endfor %}
      containers:
        - name: mydepl
          image: '{{ image }}'
          args:
            - '{{ server }}'

The content of the file data.dev is:

hostAliases = [
  {'IP': '10.11.2.8', 'HOSTNAME': 'cde.com'},
  {'IP': '10.11.5.2', 'HOSTNAME': 'abc.com'}
]

image =  "registry:5000/user/myimage:latest"
server = "https://server.inter:8443"

And the python script is:

file_loader = FileSystemLoader(searchpath='./')
env = Environment(loader=file_loader)
env.trim_blocks = True

template = env.get_template('depl.yaml.j2')

file = 'data.dev'
with open(file, 'r') as file:
    stream = file.read()
    output = template.render(stream)
    print(output)

I tried to import the file as json, yaml, raw... But actually I don't know how to deal with this kind of file, looks like the data inside the data.dev file are variables. I mean, because if I move the content of the file to the script like this:

hostAliases = [
  {'IP': '10.11.2.8', 'HOSTNAME': 'cde.com'},
  {'IP': '10.11.5.2', 'HOSTNAME': 'abc.com'}
]

image =  "registry:5000/user/myimage:latest"
server = "https://server.inter:8443"

file_loader = FileSystemLoader(searchpath='./')
env = Environment(loader=file_loader)
env.trim_blocks = True

template = env.get_template('depl.yaml.j2')

output = template.render(hostAliases = hostAliases, image = image, server = server)
print(output)

it works like a charm. So, anyone knows what I need to do?

Thx a lot!


Solution

  • It was easier to change the data.dev file to pure yaml instead of working out a way to parse it.

    The file became like:

    hostAliases:
      - IP: 10.11.6.4
        HOSTNAME: abc.com
      - IP: 10.1.1.8
        HOSTNAME: cde.com
    server: https://bla.intern:8443
    
    image: imagehost:5000/asc/image_a:latest
    

    And the script became:

    file_loader = FileSystemLoader(searchpath='templates')
    env = Environment(loader=file_loader)
    env.trim_blocks = True
    
    template = env.get_template('depl.yaml.j2')
    
    file = 'data.dev'
    with open(file, 'r') as file:
        stream = file.read()
        output = template.render(stream)
        print(output)