Aller au contenu principal

Templating Jinja2

Sherpack utilise MiniJinja, une implémentation Rust de Jinja2.

Syntaxe de base

Expressions

# Variables
name: {{ values.name }}

# Accès aux propriétés
image: {{ values.image.repository }}:{{ values.image.tag }}

# Valeurs par défaut
port: {{ values.port | default(8080) }}

Blocs de contrôle

{% if values.enabled %}
enabled: true
{% endif %}

{% for item in values.items %}
- {{ item }}
{% endfor %}

Commentaires

{# Ceci est un commentaire #}

Variables disponibles

values

Les valeurs fusionnées depuis values.yaml et les overrides :

replicas: {{ values.replicaCount }}
image: {{ values.image.repository }}

release

Informations sur le release :

name: {{ release.name }}              # Nom du release
namespace: {{ release.namespace }} # Namespace cible

pack

Métadonnées du pack :

app: {{ pack.name }}                  # Nom du pack
version: {{ pack.version }} # Version
description: {{ pack.description }} # Description

capabilities

Informations sur le cluster :

kubeVersion: {{ capabilities.kubeVersion }}

Structures de contrôle

Conditions

{% if values.ingress.enabled %}
apiVersion: networking.k8s.io/v1
kind: Ingress
...
{% endif %}

{% if values.env == "production" %}
replicas: 3
{% elif values.env == "staging" %}
replicas: 2
{% else %}
replicas: 1
{% endif %}

Boucles

{% for key, value in values.env %}
- name: {{ key }}
value: {{ value | quote }}
{% endfor %}

{% for host in values.ingress.hosts %}
- host: {{ host.name }}
paths:
{% for path in host.paths %}
- path: {{ path }}
{% endfor %}
{% endfor %}

Assignation

{% set fullName = release.name ~ "-" ~ pack.name %}
name: {{ fullName }}

Filtres courants

# Sérialisation
{{ values.config | toyaml | indent(2) }}
{{ values.data | tojson }}

# Strings
{{ values.name | upper }}
{{ values.name | lower }}
{{ "my-app" | kebabcase }}
{{ "my_app" | snakecase }}

# Encodage
{{ values.secret | b64encode }}
{{ values.encoded | b64decode }}

# Indentation
{{ values.config | toyaml | indent(4) }}
{{ values.config | toyaml | nindent(4) }}

# Sécurité
{{ values.name | quote }}
{{ values.count | required("count est requis") }}

Macros (Helpers)

Définition

# templates/_helpers.tpl
{% macro fullname() %}
{{- release.name }}-{{ pack.name }}
{%- endmacro %}

{% macro labels() %}
app.kubernetes.io/name: {{ pack.name }}
app.kubernetes.io/instance: {{ release.name }}
{%- endmacro %}

Utilisation

{% from "_helpers.tpl" import fullname, labels %}

metadata:
name: {{ fullname() }}
labels:
{{ labels() | indent(4) }}

Whitespace control

# Supprimer les espaces avant
{{- values.name }}

# Supprimer les espaces après
{{ values.name -}}

# Les deux
{{- values.name -}}

# Dans les blocs
{%- if condition %}
...
{%- endif %}

Prochaines étapes