模板继承

我们可以把不容易变动的功能放在父模板中,其他模板只需要继承改模板。
举例说明:
第一步创建父模板

# cat pod-parent.yaml.j2
apiversion: v1
kind: Pod
metadata:
{% block metadata %}
{% endblock %}
spec:
  containers:
  {% block containers %}
  {% endblock %}

第二步:引用上面的父模板

# cat pod.yaml.j2
{% extends 'pod-parent.yaml.j2' %}
{% block metadata %}
  name: {{ pod_name }}
  namespace: {{ ns_name }}
  lables:
    prometheus.io/scrape: true
{% endblock %}
{% block containers %}
  - name: {{ container_name }}
    image: {{ image_name }}
    command: {{ cmd_name }}
{% endblock %}

第三步: 渲染

j2('config_file','templates','pod.yaml.j2','pod.yaml',pod_name='test',ns_name='default',container_name='test',image_name='python',cmd_name='sh -c "python3 -m http.server"')

最终解析结果

# cat pod-parent.yaml.j2
apiversion: v1
kind: Pod
metadata:

  name: test
  namespace: default
  lables:
    prometheus.io/scrape: true

spec:
  containers:
  
  - name: test
    image: python
    command: sh -c "python3 -m http.server"
posted @ 2023-01-28 18:21  mingtian是吧  阅读(20)  评论(0编辑  收藏  举报