0
# Template Operations
1
2
This document covers OpenShift template operations, including parameter processing, template instantiation, and template instance management.
3
4
## Core Imports
5
6
```java { .api }
7
import io.fabric8.openshift.client.OpenShiftClient;
8
import io.fabric8.openshift.api.model.Template;
9
import io.fabric8.openshift.api.model.TemplateList;
10
import io.fabric8.openshift.api.model.TemplateInstance;
11
import io.fabric8.openshift.api.model.TemplateInstanceList;
12
import io.fabric8.openshift.api.model.BrokerTemplateInstance;
13
import io.fabric8.openshift.api.model.BrokerTemplateInstanceList;
14
import io.fabric8.openshift.api.model.Parameter;
15
import io.fabric8.openshift.client.dsl.TemplateResource;
16
import io.fabric8.kubernetes.client.dsl.ParameterMixedOperation;
17
import io.fabric8.kubernetes.client.dsl.Resource;
18
import io.fabric8.kubernetes.api.model.HasMetadata;
19
import io.fabric8.kubernetes.api.model.KubernetesResourceList;
20
```
21
22
## Template Operations
23
24
### Basic Template Operations
25
26
```java { .api }
27
// List all templates in a namespace
28
TemplateList templates = client.templates()
29
.inNamespace("my-project")
30
.list();
31
32
// Get a specific template
33
Template template = client.templates()
34
.inNamespace("my-project")
35
.withName("my-app-template")
36
.get();
37
38
// List templates with label selector
39
TemplateList appTemplates = client.templates()
40
.inNamespace("my-project")
41
.withLabel("category", "web-apps")
42
.list();
43
```
44
45
### Creating Templates
46
47
```java { .api }
48
// Create a new template
49
Template newTemplate = new TemplateBuilder()
50
.withNewMetadata()
51
.withName("nodejs-app-template")
52
.withNamespace("my-project")
53
.addToLabels("category", "web-apps")
54
.addToAnnotations("description", "Node.js application template")
55
.endMetadata()
56
.addNewParameter()
57
.withName("APP_NAME")
58
.withDisplayName("Application Name")
59
.withDescription("The name of the application")
60
.withRequired(true)
61
.endParameter()
62
.addNewParameter()
63
.withName("IMAGE_TAG")
64
.withDisplayName("Image Tag")
65
.withDescription("The tag for the Docker image")
66
.withValue("latest")
67
.endParameter()
68
.addNewParameter()
69
.withName("REPLICAS")
70
.withDisplayName("Replica Count")
71
.withDescription("Number of application replicas")
72
.withValue("3")
73
.endParameter()
74
.addNewObject()
75
// DeploymentConfig object
76
.withNewRaw(Map.of(
77
"apiVersion", "apps.openshift.io/v1",
78
"kind", "DeploymentConfig",
79
"metadata", Map.of(
80
"name", "${APP_NAME}",
81
"labels", Map.of("app", "${APP_NAME}")
82
),
83
"spec", Map.of(
84
"replicas", "${{REPLICAS}}",
85
"selector", Map.of("app", "${APP_NAME}"),
86
"template", Map.of(
87
"metadata", Map.of(
88
"labels", Map.of("app", "${APP_NAME}")
89
),
90
"spec", Map.of(
91
"containers", List.of(Map.of(
92
"name", "${APP_NAME}",
93
"image", "nodejs:${IMAGE_TAG}",
94
"ports", List.of(Map.of("containerPort", 8080))
95
))
96
)
97
)
98
)
99
))
100
.endObject()
101
.addNewObject()
102
// Service object
103
.withNewRaw(Map.of(
104
"apiVersion", "v1",
105
"kind", "Service",
106
"metadata", Map.of(
107
"name", "${APP_NAME}",
108
"labels", Map.of("app", "${APP_NAME}")
109
),
110
"spec", Map.of(
111
"ports", List.of(Map.of(
112
"port", 8080,
113
"targetPort", 8080
114
)),
115
"selector", Map.of("app", "${APP_NAME}")
116
)
117
))
118
.endObject()
119
.build();
120
121
Template created = client.templates()
122
.inNamespace("my-project")
123
.create(newTemplate);
124
```
125
126
## Parameter Operations
127
128
### Template Parameters
129
130
```java { .api }
131
// Get template parameters
132
Template template = client.templates()
133
.inNamespace("my-project")
134
.withName("my-app-template")
135
.get();
136
137
List<Parameter> parameters = template.getParameters();
138
for (Parameter param : parameters) {
139
System.out.println("Parameter: " + param.getName());
140
System.out.println(" Display Name: " + param.getDisplayName());
141
System.out.println(" Description: " + param.getDescription());
142
System.out.println(" Required: " + param.getRequired());
143
System.out.println(" Value: " + param.getValue());
144
System.out.println(" From: " + param.getFrom());
145
}
146
```
147
148
### Processing Templates with Parameters
149
150
```java { .api }
151
// Process template with specific parameter values
152
Template processed = client.templates()
153
.inNamespace("my-project")
154
.withName("my-app-template")
155
.withParameter("APP_NAME", "my-nodejs-app")
156
.withParameter("IMAGE_TAG", "14-ubi8")
157
.withParameter("REPLICAS", "5")
158
.process();
159
160
// Process template with parameter map
161
Map<String, String> parameters = Map.of(
162
"APP_NAME", "my-nodejs-app",
163
"IMAGE_TAG", "14-ubi8",
164
"REPLICAS", "5"
165
);
166
167
Template processedWithMap = client.templates()
168
.inNamespace("my-project")
169
.withName("my-app-template")
170
.withParameters(parameters)
171
.process();
172
```
173
174
## Template Processing and Instantiation
175
176
### Direct Template Processing
177
178
```java { .api }
179
// Process and get the objects
180
Template processed = client.templates()
181
.inNamespace("my-project")
182
.withName("my-app-template")
183
.withParameter("APP_NAME", "my-app")
184
.process();
185
186
// Extract and create objects from processed template
187
List<HasMetadata> objects = processed.getObjects();
188
for (HasMetadata object : objects) {
189
client.resource(object).createOrReplace();
190
}
191
```
192
193
### Template Processing with Validation
194
195
```java { .api }
196
// Process template with parameter validation
197
Template template = client.templates()
198
.inNamespace("my-project")
199
.withName("my-app-template")
200
.get();
201
202
// Validate required parameters
203
List<Parameter> requiredParams = template.getParameters().stream()
204
.filter(Parameter::getRequired)
205
.collect(Collectors.toList());
206
207
Map<String, String> paramValues = new HashMap<>();
208
paramValues.put("APP_NAME", "validated-app");
209
paramValues.put("REPLICAS", "3");
210
211
// Check if all required parameters are provided
212
for (Parameter param : requiredParams) {
213
if (!paramValues.containsKey(param.getName())) {
214
throw new IllegalArgumentException(
215
"Required parameter missing: " + param.getName());
216
}
217
}
218
219
// Process with validated parameters
220
Template processed = client.templates()
221
.inNamespace("my-project")
222
.withName("my-app-template")
223
.withParameters(paramValues)
224
.process();
225
```
226
227
## TemplateInstance Operations
228
229
### Creating TemplateInstances
230
231
```java { .api }
232
// Create template instance
233
TemplateInstance templateInstance = new TemplateInstanceBuilder()
234
.withNewMetadata()
235
.withName("my-app-instance")
236
.withNamespace("my-project")
237
.endMetadata()
238
.withNewSpec()
239
.withNewTemplate()
240
.withNewMetadata()
241
.withName("my-app-template")
242
.withNamespace("my-project")
243
.endMetadata()
244
.endTemplate()
245
.addNewParameter()
246
.withName("APP_NAME")
247
.withValue("my-instance-app")
248
.endParameter()
249
.addNewParameter()
250
.withName("REPLICAS")
251
.withValue("2")
252
.endParameter()
253
.endSpec()
254
.build();
255
256
TemplateInstance created = client.templateInstances()
257
.inNamespace("my-project")
258
.create(templateInstance);
259
```
260
261
### TemplateInstance Status
262
263
```java { .api }
264
// Get template instance status
265
TemplateInstance instance = client.templateInstances()
266
.inNamespace("my-project")
267
.withName("my-app-instance")
268
.get();
269
270
List<TemplateInstanceCondition> conditions = instance.getStatus().getConditions();
271
for (TemplateInstanceCondition condition : conditions) {
272
System.out.println("Condition: " + condition.getType());
273
System.out.println(" Status: " + condition.getStatus());
274
System.out.println(" Reason: " + condition.getReason());
275
System.out.println(" Message: " + condition.getMessage());
276
}
277
278
// Check if template instance is ready
279
boolean isReady = conditions.stream()
280
.anyMatch(condition ->
281
"Ready".equals(condition.getType()) &&
282
"True".equals(condition.getStatus()));
283
```
284
285
### Managing TemplateInstance Objects
286
287
```java { .api }
288
// List template instances
289
TemplateInstanceList instances = client.templateInstances()
290
.inNamespace("my-project")
291
.list();
292
293
// Get objects created by template instance
294
TemplateInstance instance = client.templateInstances()
295
.inNamespace("my-project")
296
.withName("my-app-instance")
297
.get();
298
299
List<TemplateInstanceObject> createdObjects = instance.getStatus().getObjects();
300
for (TemplateInstanceObject obj : createdObjects) {
301
System.out.println("Created object: " + obj.getRef().getKind() +
302
"/" + obj.getRef().getName());
303
}
304
```
305
306
## BrokerTemplateInstance Operations
307
308
### Cluster-scoped Template Instances
309
310
```java { .api }
311
// List broker template instances (cluster-scoped)
312
BrokerTemplateInstanceList brokerInstances = client.brokerTemplateInstances().list();
313
314
// Get specific broker template instance
315
BrokerTemplateInstance brokerInstance = client.brokerTemplateInstances()
316
.withName("cluster-template-instance")
317
.get();
318
319
// Create broker template instance
320
BrokerTemplateInstance newBrokerInstance = new BrokerTemplateInstanceBuilder()
321
.withNewMetadata()
322
.withName("shared-template-instance")
323
.endMetadata()
324
.withNewSpec()
325
.withNewTemplateInstance()
326
.withNewMetadata()
327
.withName("shared-app-instance")
328
.withNamespace("shared-project")
329
.endMetadata()
330
.withNewSpec()
331
.withNewTemplate()
332
.withNewMetadata()
333
.withName("shared-template")
334
.withNamespace("openshift")
335
.endMetadata()
336
.endTemplate()
337
.endSpec()
338
.endTemplateInstance()
339
.withNewBindingIDs("binding-12345")
340
.endSpec()
341
.build();
342
343
BrokerTemplateInstance created = client.brokerTemplateInstances()
344
.create(newBrokerInstance);
345
```
346
347
## Advanced Template Operations
348
349
### Template Watching and Monitoring
350
351
```java { .api }
352
// Watch template changes
353
client.templates()
354
.inNamespace("my-project")
355
.watch(new Watcher<Template>() {
356
@Override
357
public void eventReceived(Action action, Template template) {
358
System.out.println("Template " + action + ": " +
359
template.getMetadata().getName());
360
}
361
362
@Override
363
public void onClose(WatcherException cause) {
364
System.out.println("Template watch closed: " + cause.getMessage());
365
}
366
});
367
368
// Watch template instance changes
369
client.templateInstances()
370
.inNamespace("my-project")
371
.watch(new Watcher<TemplateInstance>() {
372
@Override
373
public void eventReceived(Action action, TemplateInstance instance) {
374
System.out.println("TemplateInstance " + action + ": " +
375
instance.getMetadata().getName());
376
377
if (instance.getStatus() != null) {
378
List<TemplateInstanceCondition> conditions =
379
instance.getStatus().getConditions();
380
conditions.forEach(condition ->
381
System.out.println(" " + condition.getType() +
382
": " + condition.getStatus()));
383
}
384
}
385
386
@Override
387
public void onClose(WatcherException cause) {
388
System.out.println("TemplateInstance watch closed: " + cause.getMessage());
389
}
390
});
391
```
392
393
### Template Export and Import
394
395
```java { .api }
396
// Export template to YAML
397
Template template = client.templates()
398
.inNamespace("my-project")
399
.withName("my-app-template")
400
.get();
401
402
String templateYaml = Serialization.asYaml(template);
403
System.out.println(templateYaml);
404
405
// Import template from YAML
406
Template imported = Serialization.unmarshal(templateYaml, Template.class);
407
Template created = client.templates()
408
.inNamespace("target-project")
409
.create(imported);
410
```
411
412
## Usage Examples
413
414
### Complete Template Workflow Example
415
416
```java
417
import io.fabric8.openshift.client.OpenShiftClient;
418
import io.fabric8.openshift.api.model.*;
419
420
public class TemplateManager {
421
private final OpenShiftClient client;
422
423
public TemplateManager(OpenShiftClient client) {
424
this.client = client;
425
}
426
427
public void deployFromTemplate(String namespace, String templateName,
428
Map<String, String> parameters) {
429
// 1. Get template
430
Template template = client.templates()
431
.inNamespace(namespace)
432
.withName(templateName)
433
.get();
434
435
if (template == null) {
436
throw new RuntimeException("Template not found: " + templateName);
437
}
438
439
// 2. Validate parameters
440
validateParameters(template, parameters);
441
442
// 3. Process template
443
Template processed = client.templates()
444
.inNamespace(namespace)
445
.withName(templateName)
446
.withParameters(parameters)
447
.process();
448
449
// 4. Create objects
450
List<HasMetadata> objects = processed.getObjects();
451
List<HasMetadata> created = new ArrayList<>();
452
453
for (HasMetadata object : objects) {
454
try {
455
HasMetadata createdObject = client.resource(object)
456
.createOrReplace();
457
created.add(createdObject);
458
System.out.println("Created: " + object.getKind() +
459
"/" + object.getMetadata().getName());
460
} catch (Exception e) {
461
System.err.println("Failed to create " + object.getKind() +
462
"/" + object.getMetadata().getName() + ": " + e.getMessage());
463
// Rollback created objects
464
rollbackCreatedObjects(created);
465
throw e;
466
}
467
}
468
469
System.out.println("Successfully deployed template: " + templateName);
470
}
471
472
private void validateParameters(Template template, Map<String, String> parameters) {
473
List<Parameter> templateParams = template.getParameters();
474
475
// Check required parameters
476
for (Parameter param : templateParams) {
477
if (param.getRequired() && !parameters.containsKey(param.getName())) {
478
throw new IllegalArgumentException(
479
"Required parameter missing: " + param.getName() +
480
" (" + param.getDisplayName() + ")");
481
}
482
}
483
484
// Set default values for missing optional parameters
485
for (Parameter param : templateParams) {
486
if (!parameters.containsKey(param.getName()) && param.getValue() != null) {
487
parameters.put(param.getName(), param.getValue());
488
}
489
}
490
}
491
492
private void rollbackCreatedObjects(List<HasMetadata> created) {
493
for (HasMetadata object : created) {
494
try {
495
client.resource(object).delete();
496
System.out.println("Rolled back: " + object.getKind() +
497
"/" + object.getMetadata().getName());
498
} catch (Exception e) {
499
System.err.println("Failed to rollback " + object.getKind() +
500
"/" + object.getMetadata().getName() + ": " + e.getMessage());
501
}
502
}
503
}
504
505
public TemplateInstance createTemplateInstance(String namespace, String templateName,
506
String instanceName,
507
Map<String, String> parameters) {
508
TemplateInstanceBuilder builder = new TemplateInstanceBuilder()
509
.withNewMetadata()
510
.withName(instanceName)
511
.withNamespace(namespace)
512
.endMetadata()
513
.withNewSpec()
514
.withNewTemplate()
515
.withNewMetadata()
516
.withName(templateName)
517
.withNamespace(namespace)
518
.endMetadata()
519
.endTemplate();
520
521
// Add parameters
522
for (Map.Entry<String, String> entry : parameters.entrySet()) {
523
builder.editSpec()
524
.addNewParameter()
525
.withName(entry.getKey())
526
.withValue(entry.getValue())
527
.endParameter()
528
.endSpec();
529
}
530
531
TemplateInstance instance = builder.build();
532
533
TemplateInstance created = client.templateInstances()
534
.inNamespace(namespace)
535
.create(instance);
536
537
// Wait for template instance to be ready
538
waitForTemplateInstanceReady(namespace, instanceName);
539
540
return created;
541
}
542
543
private void waitForTemplateInstanceReady(String namespace, String instanceName) {
544
client.templateInstances()
545
.inNamespace(namespace)
546
.withName(instanceName)
547
.waitUntilCondition(instance -> {
548
if (instance.getStatus() == null ||
549
instance.getStatus().getConditions() == null) {
550
return false;
551
}
552
553
return instance.getStatus().getConditions().stream()
554
.anyMatch(condition ->
555
"Ready".equals(condition.getType()) &&
556
"True".equals(condition.getStatus()));
557
}, 5, TimeUnit.MINUTES);
558
}
559
}
560
```
561
562
### Template Library Management Example
563
564
```java
565
public class TemplateLibrary {
566
private final OpenShiftClient client;
567
568
public TemplateLibrary(OpenShiftClient client) {
569
this.client = client;
570
}
571
572
public void installTemplateLibrary(String libraryNamespace,
573
String targetNamespace) {
574
// Get all templates from library namespace
575
TemplateList libraryTemplates = client.templates()
576
.inNamespace(libraryNamespace)
577
.list();
578
579
for (Template template : libraryTemplates.getItems()) {
580
// Clone template to target namespace
581
Template cloned = new TemplateBuilder(template)
582
.editMetadata()
583
.withNamespace(targetNamespace)
584
.withResourceVersion(null) // Clear resource version
585
.withUid(null) // Clear UID
586
.endMetadata()
587
.build();
588
589
try {
590
client.templates()
591
.inNamespace(targetNamespace)
592
.createOrReplace(cloned);
593
594
System.out.println("Installed template: " +
595
template.getMetadata().getName());
596
} catch (Exception e) {
597
System.err.println("Failed to install template " +
598
template.getMetadata().getName() + ": " + e.getMessage());
599
}
600
}
601
}
602
603
public List<Template> findTemplatesByCategory(String namespace, String category) {
604
return client.templates()
605
.inNamespace(namespace)
606
.withLabel("category", category)
607
.list()
608
.getItems();
609
}
610
}
611
```
612
613
## Types
614
615
### Template
616
617
```java { .api }
618
public class Template implements HasMetadata {
619
public ObjectMeta getMetadata();
620
public List<Parameter> getParameters();
621
public List<HasMetadata> getObjects();
622
public Map<String, String> getLabels();
623
public String getMessage();
624
}
625
626
public class Parameter {
627
public String getName();
628
public String getDisplayName();
629
public String getDescription();
630
public String getValue();
631
public Boolean getRequired();
632
public String getFrom();
633
public String getGenerate();
634
}
635
```
636
637
### TemplateInstance
638
639
```java { .api }
640
public class TemplateInstance implements HasMetadata {
641
public ObjectMeta getMetadata();
642
public TemplateInstanceSpec getSpec();
643
public TemplateInstanceStatus getStatus();
644
}
645
646
public class TemplateInstanceSpec {
647
public TemplateInstanceRequester getRequester();
648
public Template getTemplate();
649
public List<Parameter> getParameters();
650
public ObjectReference getSecret();
651
}
652
653
public class TemplateInstanceStatus {
654
public List<TemplateInstanceCondition> getConditions();
655
public List<TemplateInstanceObject> getObjects();
656
}
657
658
public class TemplateInstanceCondition {
659
public String getType(); // InstantiateFailure, Ready
660
public String getStatus(); // True, False, Unknown
661
public String getLastTransitionTime();
662
public String getReason();
663
public String getMessage();
664
}
665
666
public class TemplateInstanceObject {
667
public ObjectReference getRef();
668
}
669
```
670
671
### TemplateResource DSL
672
673
```java { .api }
674
public interface TemplateResource extends Resource<Template> {
675
Template process();
676
TemplateResource withParameter(String name, String value);
677
TemplateResource withParameters(Map<String, String> parameters);
678
}
679
```
680
681
### BrokerTemplateInstance
682
683
```java { .api }
684
public class BrokerTemplateInstance implements HasMetadata {
685
public ObjectMeta getMetadata();
686
public BrokerTemplateInstanceSpec getSpec();
687
}
688
689
public class BrokerTemplateInstanceSpec {
690
public TemplateInstance getTemplateInstance();
691
public List<String> getBindingIDs();
692
}
693
```