Skip to content

Commit 90fb9d5

Browse files
Add documentation and example for Yaml.createResource() feature
Co-authored-by: brendandburns <[email protected]>
1 parent 551da66 commit 90fb9d5

File tree

2 files changed

+219
-0
lines changed

2 files changed

+219
-0
lines changed

docs/yaml-create-resource.md

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
# Creating Kubernetes Resources from YAML
2+
3+
This feature allows you to create Kubernetes resources from YAML without having to specify the resource type upfront, similar to `kubectl create -f file.yaml`.
4+
5+
## Overview
6+
7+
The `Yaml.createResource()` methods automatically:
8+
1. Parse the YAML to extract `apiVersion` and `kind`
9+
2. Determine the appropriate Java class for the resource type
10+
3. Load the YAML into that strongly-typed object
11+
4. Use the GenericKubernetesApi to create the resource in the cluster
12+
13+
## Usage
14+
15+
### Create from YAML String
16+
17+
```java
18+
ApiClient client = Config.defaultClient();
19+
20+
String yaml =
21+
"apiVersion: v1\n" +
22+
"kind: ConfigMap\n" +
23+
"metadata:\n" +
24+
" name: my-config\n" +
25+
" namespace: default\n" +
26+
"data:\n" +
27+
" key: value\n";
28+
29+
Object resource = Yaml.createResource(client, yaml);
30+
```
31+
32+
### Create from YAML File
33+
34+
```java
35+
ApiClient client = Config.defaultClient();
36+
File yamlFile = new File("my-resource.yaml");
37+
38+
Object resource = Yaml.createResource(client, yamlFile);
39+
```
40+
41+
### Create from Reader
42+
43+
```java
44+
ApiClient client = Config.defaultClient();
45+
Reader reader = new FileReader("my-resource.yaml");
46+
47+
Object resource = Yaml.createResource(client, reader);
48+
```
49+
50+
## Type Casting
51+
52+
The returned object is the strongly-typed Kubernetes object, so you can cast it if needed:
53+
54+
```java
55+
Object result = Yaml.createResource(client, yaml);
56+
57+
if (result instanceof V1ConfigMap) {
58+
V1ConfigMap configMap = (V1ConfigMap) result;
59+
System.out.println("Created ConfigMap: " + configMap.getMetadata().getName());
60+
}
61+
```
62+
63+
## Supported Resources
64+
65+
This feature works with any Kubernetes resource type that is registered in the ModelMapper, including:
66+
- Core resources (Pod, Service, ConfigMap, Secret, etc.)
67+
- Apps resources (Deployment, StatefulSet, DaemonSet, etc.)
68+
- Custom resources that have been registered
69+
70+
## Error Handling
71+
72+
The method throws:
73+
- `IOException` if there's an error reading or parsing the YAML
74+
- `ApiException` if there's an error creating the resource in the cluster
75+
76+
```java
77+
try {
78+
Object resource = Yaml.createResource(client, yaml);
79+
System.out.println("Resource created successfully");
80+
} catch (IOException e) {
81+
System.err.println("Failed to parse YAML: " + e.getMessage());
82+
} catch (ApiException e) {
83+
System.err.println("Failed to create resource: " + e.getMessage());
84+
}
85+
```
86+
87+
## Comparison with Kubectl
88+
89+
This feature provides Java equivalent functionality to:
90+
91+
```bash
92+
kubectl create -f resource.yaml
93+
```
94+
95+
Instead of having to know the resource type in advance and use type-specific APIs:
96+
97+
```java
98+
// Old way - you need to know it's a ConfigMap
99+
V1ConfigMap configMap = Yaml.loadAs(yaml, V1ConfigMap.class);
100+
CoreV1Api api = new CoreV1Api();
101+
api.createNamespacedConfigMap("default", configMap).execute();
102+
103+
// New way - works with any resource type
104+
Object resource = Yaml.createResource(client, yaml);
105+
```
106+
107+
## Discovery and Resource Mapping
108+
109+
The feature uses API discovery to determine the correct resource plural name and API group. On first use, it may perform discovery to refresh the ModelMapper cache. Subsequent calls will use the cached information.
110+
111+
## See Also
112+
113+
- [YamlCreateResourceExample.java](../examples/examples-release-latest/src/main/java/io/kubernetes/client/examples/YamlCreateResourceExample.java) - Complete working example
114+
- [YamlCreateResourceTest.java](../util/src/test/java/io/kubernetes/client/util/YamlCreateResourceTest.java) - Comprehensive tests
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
/*
2+
Copyright 2020 The Kubernetes Authors.
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
Unless required by applicable law or agreed to in writing, software
8+
distributed under the License is distributed on an "AS IS" BASIS,
9+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10+
See the License for the specific language governing permissions and
11+
limitations under the License.
12+
*/
13+
package io.kubernetes.client.examples;
14+
15+
import io.kubernetes.client.openapi.ApiClient;
16+
import io.kubernetes.client.openapi.ApiException;
17+
import io.kubernetes.client.openapi.Configuration;
18+
import io.kubernetes.client.openapi.apis.CoreV1Api;
19+
import io.kubernetes.client.openapi.models.V1ConfigMap;
20+
import io.kubernetes.client.openapi.models.V1Pod;
21+
import io.kubernetes.client.util.Config;
22+
import io.kubernetes.client.util.Yaml;
23+
import java.io.File;
24+
import java.io.IOException;
25+
26+
/**
27+
* A simple example of how to use Yaml.createResource() to create Kubernetes resources from YAML
28+
* without specifying the type upfront. This is equivalent to `kubectl create -f <yaml-file>`.
29+
*
30+
* <p>Easiest way to run this: mvn exec:java
31+
* -Dexec.mainClass="io.kubernetes.client.examples.YamlCreateResourceExample"
32+
*
33+
* <p>From inside $REPO_DIR/examples
34+
*/
35+
public class YamlCreateResourceExample {
36+
public static void main(String[] args) throws IOException, ApiException {
37+
// Initialize the API client
38+
ApiClient client = Config.defaultClient();
39+
Configuration.setDefaultApiClient(client);
40+
41+
// Example 1: Create a ConfigMap from YAML string
42+
// This method automatically determines the resource type (ConfigMap)
43+
// and uses the appropriate API to create it
44+
String configMapYaml =
45+
"apiVersion: v1\n"
46+
+ "kind: ConfigMap\n"
47+
+ "metadata:\n"
48+
+ " name: example-config\n"
49+
+ " namespace: default\n"
50+
+ "data:\n"
51+
+ " database.url: jdbc:postgresql://localhost/mydb\n"
52+
+ " database.user: admin\n";
53+
54+
System.out.println("Creating ConfigMap from YAML string...");
55+
Object configMapResult = Yaml.createResource(client, configMapYaml);
56+
System.out.println("Created: " + configMapResult);
57+
58+
// Example 2: Create a Pod from YAML string
59+
// Again, no need to specify V1Pod.class - the method determines it automatically
60+
String podYaml =
61+
"apiVersion: v1\n"
62+
+ "kind: Pod\n"
63+
+ "metadata:\n"
64+
+ " name: example-pod\n"
65+
+ " namespace: default\n"
66+
+ "spec:\n"
67+
+ " containers:\n"
68+
+ " - name: nginx\n"
69+
+ " image: nginx:1.14.2\n"
70+
+ " ports:\n"
71+
+ " - containerPort: 80\n";
72+
73+
System.out.println("\nCreating Pod from YAML string...");
74+
Object podResult = Yaml.createResource(client, podYaml);
75+
System.out.println("Created: " + podResult);
76+
77+
// Example 3: Create a resource from a YAML file
78+
// This works with any Kubernetes resource type
79+
File yamlFile = new File("example-resource.yaml");
80+
if (yamlFile.exists()) {
81+
System.out.println("\nCreating resource from YAML file...");
82+
Object fileResult = Yaml.createResource(client, yamlFile);
83+
System.out.println("Created: " + fileResult);
84+
}
85+
86+
// Example 4: Type casting if you need to access specific fields
87+
// The returned object is the strongly-typed Kubernetes object
88+
V1ConfigMap configMap = (V1ConfigMap) configMapResult;
89+
System.out.println("\nConfigMap name: " + configMap.getMetadata().getName());
90+
System.out.println("ConfigMap data: " + configMap.getData());
91+
92+
V1Pod pod = (V1Pod) podResult;
93+
System.out.println("\nPod name: " + pod.getMetadata().getName());
94+
System.out.println("Pod phase: " + pod.getStatus().getPhase());
95+
96+
// Clean up - delete the created resources
97+
CoreV1Api api = new CoreV1Api();
98+
System.out.println("\nCleaning up...");
99+
api.deleteNamespacedConfigMap("example-config", "default").execute();
100+
System.out.println("Deleted ConfigMap");
101+
102+
api.deleteNamespacedPod("example-pod", "default").execute();
103+
System.out.println("Deleted Pod");
104+
}
105+
}

0 commit comments

Comments
 (0)