-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Add Yaml.createResource() for type-agnostic resource creation from YAML #4427
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Copilot
wants to merge
5
commits into
master
Choose a base branch
from
copilot/extend-kubectl-create-yaml
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+558
−0
Draft
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
f96a2d3
Initial plan
Copilot 551da66
Add Yaml.createResource() methods for creating resources from arbitra…
Copilot 90fb9d5
Add documentation and example for Yaml.createResource() feature
Copilot 7013d59
Address code review comments - add clarifying comments and fix imports
Copilot 1caa15d
Address review feedback: use string buffer instead of YAML dump, remo…
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| # Creating Kubernetes Resources from YAML | ||
|
|
||
| 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`. | ||
|
|
||
| ## Overview | ||
|
|
||
| The `Yaml.createResource()` methods automatically: | ||
| 1. Parse the YAML to extract `apiVersion` and `kind` | ||
| 2. Determine the appropriate Java class for the resource type | ||
| 3. Load the YAML into that strongly-typed object | ||
| 4. Use the GenericKubernetesApi to create the resource in the cluster | ||
|
|
||
| ## Usage | ||
|
|
||
| ### Create from YAML String | ||
|
|
||
| ```java | ||
| ApiClient client = Config.defaultClient(); | ||
|
|
||
| String yaml = | ||
| "apiVersion: v1\n" + | ||
| "kind: ConfigMap\n" + | ||
| "metadata:\n" + | ||
| " name: my-config\n" + | ||
| " namespace: default\n" + | ||
| "data:\n" + | ||
| " key: value\n"; | ||
|
|
||
| Object resource = Yaml.createResource(client, yaml); | ||
| ``` | ||
|
|
||
| ### Create from YAML File | ||
|
|
||
| ```java | ||
| ApiClient client = Config.defaultClient(); | ||
| File yamlFile = new File("my-resource.yaml"); | ||
|
|
||
| Object resource = Yaml.createResource(client, yamlFile); | ||
| ``` | ||
|
|
||
| ### Create from Reader | ||
|
|
||
| ```java | ||
| ApiClient client = Config.defaultClient(); | ||
| Reader reader = new FileReader("my-resource.yaml"); | ||
|
|
||
| Object resource = Yaml.createResource(client, reader); | ||
| ``` | ||
|
|
||
| ## Type Casting | ||
|
|
||
| The returned object is the strongly-typed Kubernetes object, so you can cast it if needed: | ||
|
|
||
| ```java | ||
| Object result = Yaml.createResource(client, yaml); | ||
|
|
||
| if (result instanceof V1ConfigMap) { | ||
| V1ConfigMap configMap = (V1ConfigMap) result; | ||
| System.out.println("Created ConfigMap: " + configMap.getMetadata().getName()); | ||
| } | ||
| ``` | ||
|
|
||
| ## Supported Resources | ||
|
|
||
| This feature works with any Kubernetes resource type that is registered in the ModelMapper, including: | ||
| - Core resources (Pod, Service, ConfigMap, Secret, etc.) | ||
| - Apps resources (Deployment, StatefulSet, DaemonSet, etc.) | ||
| - Custom resources that have been registered | ||
|
|
||
| ## Error Handling | ||
|
|
||
| The method throws: | ||
| - `IOException` if there's an error reading or parsing the YAML | ||
| - `ApiException` if there's an error creating the resource in the cluster | ||
|
|
||
| ```java | ||
| try { | ||
| Object resource = Yaml.createResource(client, yaml); | ||
| System.out.println("Resource created successfully"); | ||
| } catch (IOException e) { | ||
| System.err.println("Failed to parse YAML: " + e.getMessage()); | ||
| } catch (ApiException e) { | ||
| System.err.println("Failed to create resource: " + e.getMessage()); | ||
| } | ||
| ``` | ||
|
|
||
| ## Comparison with Kubectl | ||
|
|
||
| This feature provides Java equivalent functionality to: | ||
|
|
||
| ```bash | ||
| kubectl create -f resource.yaml | ||
| ``` | ||
|
|
||
| Instead of having to know the resource type in advance and use type-specific APIs: | ||
|
|
||
| ```java | ||
| // Old way - you need to know it's a ConfigMap | ||
| V1ConfigMap configMap = Yaml.loadAs(yaml, V1ConfigMap.class); | ||
| CoreV1Api api = new CoreV1Api(); | ||
| api.createNamespacedConfigMap("default", configMap).execute(); | ||
|
|
||
| // New way - works with any resource type | ||
| Object resource = Yaml.createResource(client, yaml); | ||
| ``` | ||
|
|
||
| ## Discovery and Resource Mapping | ||
|
|
||
| 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. | ||
|
|
||
| ## See Also | ||
|
|
||
| - [YamlCreateResourceExample.java](../examples/examples-release-latest/src/main/java/io/kubernetes/client/examples/YamlCreateResourceExample.java) - Complete working example | ||
| - [YamlCreateResourceTest.java](../util/src/test/java/io/kubernetes/client/util/YamlCreateResourceTest.java) - Comprehensive tests |
105 changes: 105 additions & 0 deletions
105
...release-latest/src/main/java/io/kubernetes/client/examples/YamlCreateResourceExample.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| /* | ||
| Copyright 2020 The Kubernetes Authors. | ||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
| */ | ||
| package io.kubernetes.client.examples; | ||
|
|
||
| import io.kubernetes.client.openapi.ApiClient; | ||
| import io.kubernetes.client.openapi.ApiException; | ||
| import io.kubernetes.client.openapi.Configuration; | ||
| import io.kubernetes.client.openapi.apis.CoreV1Api; | ||
| import io.kubernetes.client.openapi.models.V1ConfigMap; | ||
| import io.kubernetes.client.openapi.models.V1Pod; | ||
| import io.kubernetes.client.util.Config; | ||
| import io.kubernetes.client.util.Yaml; | ||
| import java.io.File; | ||
| import java.io.IOException; | ||
|
|
||
| /** | ||
| * A simple example of how to use Yaml.createResource() to create Kubernetes resources from YAML | ||
| * without specifying the type upfront. This is equivalent to `kubectl create -f <yaml-file>`. | ||
| * | ||
| * <p>Easiest way to run this: mvn exec:java | ||
| * -Dexec.mainClass="io.kubernetes.client.examples.YamlCreateResourceExample" | ||
| * | ||
| * <p>From inside $REPO_DIR/examples | ||
| */ | ||
| public class YamlCreateResourceExample { | ||
| public static void main(String[] args) throws IOException, ApiException { | ||
| // Initialize the API client | ||
| ApiClient client = Config.defaultClient(); | ||
| Configuration.setDefaultApiClient(client); | ||
|
|
||
| // Example 1: Create a ConfigMap from YAML string | ||
| // This method automatically determines the resource type (ConfigMap) | ||
| // and uses the appropriate API to create it | ||
| String configMapYaml = | ||
| "apiVersion: v1\n" | ||
| + "kind: ConfigMap\n" | ||
| + "metadata:\n" | ||
| + " name: example-config\n" | ||
| + " namespace: default\n" | ||
| + "data:\n" | ||
| + " database.url: jdbc:postgresql://localhost/mydb\n" | ||
| + " database.user: admin\n"; | ||
|
|
||
| System.out.println("Creating ConfigMap from YAML string..."); | ||
| Object configMapResult = Yaml.createResource(client, configMapYaml); | ||
| System.out.println("Created: " + configMapResult); | ||
|
|
||
| // Example 2: Create a Pod from YAML string | ||
| // Again, no need to specify V1Pod.class - the method determines it automatically | ||
| String podYaml = | ||
| "apiVersion: v1\n" | ||
| + "kind: Pod\n" | ||
| + "metadata:\n" | ||
| + " name: example-pod\n" | ||
| + " namespace: default\n" | ||
| + "spec:\n" | ||
| + " containers:\n" | ||
| + " - name: nginx\n" | ||
| + " image: nginx:1.14.2\n" | ||
| + " ports:\n" | ||
| + " - containerPort: 80\n"; | ||
|
|
||
| System.out.println("\nCreating Pod from YAML string..."); | ||
| Object podResult = Yaml.createResource(client, podYaml); | ||
| System.out.println("Created: " + podResult); | ||
|
|
||
| // Example 3: Create a resource from a YAML file | ||
| // This works with any Kubernetes resource type | ||
| File yamlFile = new File("example-resource.yaml"); | ||
| if (yamlFile.exists()) { | ||
| System.out.println("\nCreating resource from YAML file..."); | ||
| Object fileResult = Yaml.createResource(client, yamlFile); | ||
| System.out.println("Created: " + fileResult); | ||
| } | ||
|
|
||
| // Example 4: Type casting if you need to access specific fields | ||
| // The returned object is the strongly-typed Kubernetes object | ||
| V1ConfigMap configMap = (V1ConfigMap) configMapResult; | ||
| System.out.println("\nConfigMap name: " + configMap.getMetadata().getName()); | ||
| System.out.println("ConfigMap data: " + configMap.getData()); | ||
|
|
||
| V1Pod pod = (V1Pod) podResult; | ||
| System.out.println("\nPod name: " + pod.getMetadata().getName()); | ||
| System.out.println("Pod phase: " + pod.getStatus().getPhase()); | ||
|
|
||
| // Clean up - delete the created resources | ||
| CoreV1Api api = new CoreV1Api(); | ||
| System.out.println("\nCleaning up..."); | ||
| api.deleteNamespacedConfigMap("example-config", "default").execute(); | ||
| System.out.println("Deleted ConfigMap"); | ||
|
|
||
| api.deleteNamespacedPod("example-pod", "default").execute(); | ||
| System.out.println("Deleted Pod"); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Load the Reader into a byte array at the beginning of this function and use the same byte array in both cases vs dumping it back out to YAML.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 1caa15d. Now reads the Reader into a string buffer first and uses the same content for both parsing (to extract apiVersion/kind) and loading into the typed object.