import yaml
from jinja2 import Environment, FileSystemLoader
if __name__ == "__main__":
# Load values from YAML file
with open('./test.yaml', 'r') as f:
values = yaml.safe_load(f)
# Load Jinja environment
env = Environment(loader=FileSystemLoader('./template'), trim_blocks=True, lstrip_blocks=True)
template = env.get_template('template.j2')
# Iterate over each service route
for index, sr_data in enumerate(values["serviceRoutes"], start=1):
# Render the template for each service route
rendered = template.render(serviceRoutes={"sr{}".format(index): sr_data})
# Write the rendered content to a YAML file
with open("{}.yaml".format("sr{}".format(index)), "w") as output_file:
output_file.write(rendered)
serviceRoutes:
{% for sr_name, sr_data in serviceRoutes.items() %}
- sr:
name: {{ sr_name }}
gateways:
{% for gateway in sr_data.gateways %}
- {{ gateway }}
{% endfor %}
hosts:
{% for host in sr_data.hosts %}
- {{ host }}
{% endfor %}
http:
{% for item in sr_data.http %}
- match:
prefix: "{{ item.match.prefix }}"
{% if item.get('rewrite') %}
rewrite:
uri: "{{ item.rewrite.uri }}"
{% endif %}
route:
- destination:
{% if item.get('destination') %}
host: "{{ item['destination']['host'] }}"
port:
number: {{ item['destination']['port']['number'] }}
{% else %}
host: ""
port:
number: 0
{% endif %}
weight: {{ item['weight'] }}
{% endfor %}
{% endfor %}
serviceRoutes:
- sr:
name: sr1
gateways:
- mesh
- "test.usnabk.com"
hosts:
- "1.us.bank-dns.com"
- "tes.us.bank-dns.com"
http:
- match:
prefix: "base_path"
route:
- destination:
host: "us.bank-dns.com"
port:
number: 8080
weight: 100
- match:
prefix: "base_path"
route:
- destination:
host: "us.bank-dns.com"
port:
number: 8080
weight: 100
What I’m trying to do
Things I have tried
I am not getting destination > host port values
this is the output it is generating
serviceRoutes:
- sr:
name: sr1
gateways:
- mesh
- test.usnabk.com
hosts:
- 1.us.bank-dns.com
- tes.us.bank-dns.com
http:
- match:
prefix: "base_path"
route:
- destination:
host: ""
port:
number: 0
weight:
- match:
prefix: "base_path"
route:
- destination:
host: ""
port:
number: 0
weight: