tmpltool 1.5.0

A fast and simple command-line template rendering tool using MiniJinja templates with environment variables
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
## Kubernetes Functions

Kubernetes-specific helpers for manifest generation, label sanitization, and resource management.

**See also:** [Function Reference]../FUNCTIONS.md | [Main Documentation]../README.md

Kubernetes-specific helpers for manifest generation and label sanitization.

#### `k8s_resource_request(cpu, memory)`

Format Kubernetes resource requests in YAML format.

**Arguments:**
- `cpu` (required): CPU request - string like `"500m"` or number (converted to millicores)
- `memory` (required): Memory request - string like `"512Mi"` or number in MiB (auto-converted to Mi/Gi)

**Returns:** YAML-formatted resource request block

**Numeric conversions:**
- CPU: `0.5``"500m"`, `2``"2000m"`
- Memory: `512``"512Mi"`, `1024``"1Gi"`, `2048``"2Gi"`

**Example:**
```jinja
{# Basic usage with strings #}
{{ k8s_resource_request(cpu="500m", memory="512Mi") }}
{# Output:
requests:
  cpu: "500m"
  memory: "512Mi"
#}

{# With numeric values (auto-formatted) #}
{{ k8s_resource_request(cpu=0.5, memory=512) }}
{# Output:
requests:
  cpu: "500m"
  memory: "512Mi"
#}

{# In a Kubernetes deployment #}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  template:
    spec:
      containers:
      - name: app
        image: myapp:latest
        resources:
          {{ k8s_resource_request(cpu="1000m", memory="1Gi") | indent(10) }}
```

#### `k8s_label_safe(value)` / `| k8s_label_safe`

Sanitize string to be Kubernetes label-safe.

**Arguments:**
- `value` (required): String to sanitize

**Returns:** Sanitized string following Kubernetes label requirements:
- Max 63 characters
- Only alphanumeric, dashes, underscores, dots
- Must start and end with alphanumeric
- Lowercase

**Example:**
```jinja
{# Function syntax #}
{{ k8s_label_safe(value="My App (v2.0)") }}
{# Output: my-app-v2.0 #}

{# Filter syntax #}
{{ "My App (v2.0)" | k8s_label_safe }}
{# Output: my-app-v2.0 #}

{# Use in labels #}
metadata:
  labels:
    app: {{ app_name | k8s_label_safe }}
    version: {{ version | k8s_label_safe }}
```

#### `k8s_dns_label_safe(value)` / `| k8s_dns_label_safe`

Format DNS-safe label (max 63 chars, lowercase, alphanumeric and dashes only).

**Arguments:**
- `value` (required): String to format

**Returns:** DNS-safe string suitable for Kubernetes resource names

**Example:**
```jinja
{# Function syntax #}
{{ k8s_dns_label_safe(value="My Service Name") }}
{# Output: my-service-name #}

{# Filter syntax #}
{{ "My Service Name" | k8s_dns_label_safe }}
{# Output: my-service-name #}

{# Use in service names #}
apiVersion: v1
kind: Service
metadata:
  name: {{ service_name | k8s_dns_label_safe }}
```

#### `k8s_env_var_ref(var_name, source, name)`

Generate Kubernetes environment variable reference (ConfigMap or Secret).

**Arguments:**
- `var_name` (required): The environment variable name/key
- `source` (optional): Source type - `"configmap"` or `"secret"` (default: `"configmap"`)
- `name` (optional): Name of the ConfigMap/Secret (default: auto-generated from var_name)

**Returns:** YAML-formatted `valueFrom` reference

**Example:**
```jinja
{# ConfigMap reference #}
- name: DATABASE_HOST
  {{ k8s_env_var_ref(var_name="DATABASE_HOST", source="configmap", name="app-config") | indent(2) }}
{# Output:
  valueFrom:
    configMapKeyRef:
      name: app-config
      key: DATABASE_HOST
#}

{# Secret reference with auto-generated name #}
- name: DB_PASSWORD
  {{ k8s_env_var_ref(var_name="DB_PASSWORD", source="secret") | indent(2) }}
{# Output:
  valueFrom:
    secretKeyRef:
      name: db-password
      key: DB_PASSWORD
#}
```

#### `k8s_secret_ref(secret_name, key, optional)`

Generate Kubernetes Secret reference for environment variables.

**Arguments:**
- `secret_name` (required): Name of the Secret
- `key` (required): Key within the Secret
- `optional` (optional): Whether the Secret is optional (default: `false`)

**Returns:** YAML-formatted `valueFrom` secretKeyRef

**Example:**
```jinja
{# Basic secret reference #}
- name: DB_PASSWORD
  {{ k8s_secret_ref(secret_name="db-credentials", key="password") | indent(2) }}
{# Output:
  valueFrom:
    secretKeyRef:
      name: db-credentials
      key: password
#}

{# Optional secret #}
- name: OPTIONAL_TOKEN
  {{ k8s_secret_ref(secret_name="tokens", key="api_token", optional=true) | indent(2) }}
{# Output:
  valueFrom:
    secretKeyRef:
      name: tokens
      key: api_token
      optional: true
#}
```

#### `k8s_configmap_ref(configmap_name, key, optional)`

Generate Kubernetes ConfigMap reference for environment variables.

**Arguments:**
- `configmap_name` (required): Name of the ConfigMap
- `key` (required): Key within the ConfigMap
- `optional` (optional): Whether the ConfigMap is optional (default: `false`)

**Returns:** YAML-formatted `valueFrom` configMapKeyRef

**Example:**
```jinja
{# Basic ConfigMap reference #}
- name: DATABASE_HOST
  {{ k8s_configmap_ref(configmap_name="app-config", key="database_host") | indent(2) }}
{# Output:
  valueFrom:
    configMapKeyRef:
      name: app-config
      key: database_host
#}

{# Optional ConfigMap #}
- name: FEATURE_FLAG
  {{ k8s_configmap_ref(configmap_name="features", key="new_ui", optional=true) | indent(2) }}
{# Output:
  valueFrom:
    configMapKeyRef:
      name: features
      key: new_ui
      optional: true
#}

{# Complete deployment example #}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ k8s_dns_label_safe(value=app_name) }}
spec:
  template:
    spec:
      containers:
        - name: app
          image: myapp:latest
          env:
            - name: ENVIRONMENT
              value: "production"
            - name: DATABASE_HOST
              {{ k8s_configmap_ref(configmap_name="app-config", key="db_host") | indent(14) }}
            - name: DATABASE_PASSWORD
              {{ k8s_secret_ref(secret_name="db-credentials", key="password") | indent(14) }}
          resources:
            {{ k8s_resource_request(cpu="500m", memory="512Mi") | indent(12) }}
```

#### `helm_tpl(template, values)`

Perform Helm-style templating with `{{ .key }}` syntax.

**Arguments:**
- `template` (required): Template string with Helm-style placeholders
- `values` (required): Object containing values to substitute

**Returns:** Rendered template string

**Example:**
```jinja
{# Basic Helm templating #}
{{ helm_tpl(template="Hello {{ .name }}!", values={"name": "World"}) }}
{# Output: Hello World! #}

{# Complex template #}
{% set tpl = "{{ .app.name }}-{{ .app.version }}" %}
{% set vals = {"app": {"name": "myapp", "version": "1.0"}} %}
{{ helm_tpl(template=tpl, values=vals) }}
{# Output: myapp-1.0 #}

{# In Kubernetes manifest #}
metadata:
  name: {{ helm_tpl(template="{{ .Release.Name }}-{{ .Chart.Name }}", values={"Release": {"Name": "prod"}, "Chart": {"Name": "webapp"}}) }}
```

#### `k8s_annotation_safe(value)` / `| k8s_annotation_safe`

Sanitize a string for use as a Kubernetes annotation value.

**Arguments:**
- `value` (required): The string to sanitize

**Returns:** Sanitized string safe for annotation values (max 64KB, control chars replaced with spaces)

**Example:**
```jinja
{# Function syntax #}
{{ k8s_annotation_safe(value="Description with\nnewlines and\ttabs") }}
{# Output: Description with newlines and tabs #}

{# Filter syntax #}
{{ "Description with\nnewlines" | k8s_annotation_safe }}
{# Output: Description with newlines #}

{# In Kubernetes manifest #}
metadata:
  annotations:
    description: "{{ description | k8s_annotation_safe }}"
    config: "{{ config_obj | to_json | k8s_annotation_safe }}"
```

#### `k8s_quantity_to_bytes(quantity)`

Convert a Kubernetes quantity string to bytes.

**Arguments:**
- `quantity` (required): Kubernetes quantity string (e.g., "1Gi", "500Mi", "100m")

**Returns:** Integer number of bytes (or millicores for CPU)

**Supported suffixes:**
- Binary: Ki (1024), Mi (1024²), Gi (1024³), Ti (1024⁴), Pi (1024⁵), Ei (1024⁶)
- Decimal: K (1000), M (1000²), G (1000³), T (1000⁴), P (1000⁵), E (1000⁶)
- CPU: m (millicores)

**Example:**
```jinja
{# Convert memory quantities #}
{{ k8s_quantity_to_bytes(quantity="1Gi") }}
{# Output: 1073741824 #}

{{ k8s_quantity_to_bytes(quantity="500Mi") }}
{# Output: 524288000 #}

{# Convert CPU quantities #}
{{ k8s_quantity_to_bytes(quantity="500m") }}
{# Output: 500 (millicores) #}

{# Calculate total memory from multiple pods #}
{% set pod_memory = k8s_quantity_to_bytes(quantity="256Mi") %}
{% set replicas = 3 %}
Total bytes: {{ pod_memory * replicas }}
```

#### `k8s_bytes_to_quantity(bytes, unit)`

Convert bytes to a Kubernetes quantity string.

**Arguments:**
- `bytes` (required): Number of bytes to convert
- `unit` (optional): Target unit (default: auto-selects appropriate unit)
  - Supported: "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "K", "M", "G", "T", "P", "E"

**Returns:** Kubernetes quantity string

**Example:**
```jinja
{# Auto-select appropriate unit #}
{{ k8s_bytes_to_quantity(bytes=1073741824) }}
{# Output: 1Gi #}

{{ k8s_bytes_to_quantity(bytes=536870912) }}
{# Output: 512Mi #}

{# Force specific unit #}
{{ k8s_bytes_to_quantity(bytes=1073741824, unit="Mi") }}
{# Output: 1024Mi #}

{# In resource calculations #}
{% set total_bytes = 2147483648 %}
resources:
  requests:
    memory: "{{ k8s_bytes_to_quantity(bytes=total_bytes / 2) }}"
  limits:
    memory: "{{ k8s_bytes_to_quantity(bytes=total_bytes) }}"
```

#### `k8s_selector(labels)`

Generate a Kubernetes label selector string from a labels object.

**Arguments:**
- `labels` (required): Object containing key-value pairs for the selector

**Returns:** Label selector string in the format "key1=value1,key2=value2"

**Example:**
```jinja
{# Basic selector #}
{{ k8s_selector(labels={"app": "nginx", "env": "prod"}) }}
{# Output: app=nginx,env=prod #}

{# In Kubernetes Service #}
spec:
  selector:
    {{ k8s_selector(labels={"app": app_name, "version": version}) }}

{# With kubectl #}
kubectl get pods -l "{{ k8s_selector(labels=pod_labels) }}"
```

#### `k8s_pod_affinity(key, operator, values, topology_key, type)`

Generate Kubernetes pod affinity/anti-affinity YAML.

**Arguments:**
- `key` (required): Label key to match
- `operator` (required): Match operator ("In", "NotIn", "Exists", "DoesNotExist")
- `values` (optional): Array of values to match (required for In/NotIn)
- `topology_key` (optional): Topology key (default: "kubernetes.io/hostname")
- `type` (optional): Affinity type - "required" or "preferred" (default: "required")

**Returns:** YAML string for pod affinity configuration

**Example:**
```jinja
{# Required pod affinity #}
{{ k8s_pod_affinity(key="app", operator="In", values=["cache", "db"]) }}
{# Output:
requiredDuringSchedulingIgnoredDuringExecution:
  - labelSelector:
      matchExpressions:
        - key: app
          operator: In
          values:
            - cache
            - db
    topologyKey: kubernetes.io/hostname
#}

{# Preferred anti-affinity for spreading pods #}
{{ k8s_pod_affinity(key="app", operator="In", values=["web"], type="preferred") }}
{# Output:
preferredDuringSchedulingIgnoredDuringExecution:
  - weight: 100
    podAffinityTerm:
      labelSelector:
        matchExpressions:
          - key: app
            operator: In
            values:
              - web
      topologyKey: kubernetes.io/hostname
#}

{# In Deployment spec #}
spec:
  affinity:
    podAntiAffinity:
      {{ k8s_pod_affinity(key="app", operator="In", values=[app_name], topology_key="topology.kubernetes.io/zone") | indent(6) }}
```

#### `k8s_toleration(key, operator, value, effect)`

Generate Kubernetes toleration YAML.

**Arguments:**
- `key` (required): Taint key to tolerate
- `operator` (optional): Match operator - "Equal" or "Exists" (default: "Equal")
- `value` (optional): Taint value to match (required when operator is "Equal")
- `effect` (optional): Taint effect - "NoSchedule", "PreferNoSchedule", or "NoExecute"

**Returns:** YAML string for toleration configuration

**Example:**
```jinja
{# Basic toleration #}
{{ k8s_toleration(key="dedicated", value="gpu", effect="NoSchedule") }}
{# Output:
- key: dedicated
  operator: Equal
  value: gpu
  effect: NoSchedule
#}

{# Exists operator (matches any value) #}
{{ k8s_toleration(key="node.kubernetes.io/not-ready", operator="Exists", effect="NoExecute") }}
{# Output:
- key: node.kubernetes.io/not-ready
  operator: Exists
  effect: NoExecute
#}

{# In Pod spec #}
spec:
  tolerations:
    {{ k8s_toleration(key="dedicated", value="high-memory", effect="NoSchedule") | indent(4) }}
    {{ k8s_toleration(key="node.kubernetes.io/unreachable", operator="Exists", effect="NoExecute") | indent(4) }}
```

#### `k8s_probe(type, path, port, initial_delay, period, timeout, success_threshold, failure_threshold, command)`

Generate Kubernetes liveness/readiness probe YAML.

**Arguments:**
- `type` (required): Probe type - "http", "tcp", or "exec"
- `path` (optional): HTTP path for http probes (default: "/healthz")
- `port` (optional): Port number for http/tcp probes (default: 8080)
- `initial_delay` (optional): Initial delay in seconds (default: 0)
- `period` (optional): Period between probes in seconds (default: 10)
- `timeout` (optional): Timeout in seconds (default: 1)
- `success_threshold` (optional): Success threshold (default: 1)
- `failure_threshold` (optional): Failure threshold (default: 3)
- `command` (optional): Command array for exec probes

**Returns:** YAML string for probe configuration

**Example:**
```jinja
{# HTTP health check #}
{{ k8s_probe(type="http", path="/health", port=8080) }}
{# Output:
httpGet:
  path: /health
  port: 8080
initialDelaySeconds: 0
periodSeconds: 10
timeoutSeconds: 1
successThreshold: 1
failureThreshold: 3
#}

{# TCP socket check with custom timings #}
{{ k8s_probe(type="tcp", port=5432, initial_delay=30, period=20) }}
{# Output:
tcpSocket:
  port: 5432
initialDelaySeconds: 30
periodSeconds: 20
timeoutSeconds: 1
successThreshold: 1
failureThreshold: 3
#}

{# Exec probe with command #}
{{ k8s_probe(type="exec", command=["cat", "/tmp/healthy"]) }}
{# Output:
exec:
  command:
    - cat
    - /tmp/healthy
initialDelaySeconds: 0
periodSeconds: 10
timeoutSeconds: 1
successThreshold: 1
failureThreshold: 3
#}

{# In container spec #}
containers:
  - name: app
    livenessProbe:
      {{ k8s_probe(type="http", path="/healthz", port=8080, initial_delay=15, failure_threshold=5) | indent(6) }}
    readinessProbe:
      {{ k8s_probe(type="http", path="/ready", port=8080, period=5) | indent(6) }}
```