This client provides access to the full Kubernetes & OpenShift REST APIs via a fluent DSL.
The easiest way to create a client is:
KubernetesClient client = new KubernetesClientBuilder().build();
DefaultOpenShiftClient
implements both the KubernetesClient
& OpenShiftClient
interface so if you need the OpenShift extensions, such as Build
s, etc then simply do:
OpenShiftClient osClient = new KubernetesClientBuilder().build().adapt(OpenShiftClient.class);
This will use settings from different sources in the following order of priority:
System properties are preferred over environment variables. The following system properties & environment variables can be used for configuration:
Property / Environment Variable Description Default valuekubernetes.disable.autoConfig
/ KUBERNETES_DISABLE_AUTOCONFIG
Disable automatic configuration (KubernetesClient would not look in ~/.kube/config
, mounted ServiceAccount, environment variables or System properties for Kubernetes cluster information) false
kubernetes.master
/ KUBERNETES_MASTER
Kubernetes master URL https://kubernetes.default.svc
kubernetes.api.version
/ KUBERNETES_API_VERSION
API version v1
openshift.url
/ OPENSHIFT_URL
OpenShift master URL Kubernetes master URL value kubernetes.oapi.version
/ KUBERNETES_OAPI_VERSION
OpenShift API version v1
kubernetes.trust.certificates
/ KUBERNETES_TRUST_CERTIFICATES
Trust all certificates false
kubernetes.disable.hostname.verification
/ KUBERNETES_DISABLE_HOSTNAME_VERIFICATION
false
kubernetes.certs.ca.file
/ KUBERNETES_CERTS_CA_FILE
kubernetes.certs.ca.data
/ KUBERNETES_CERTS_CA_DATA
kubernetes.certs.client.file
/ KUBERNETES_CERTS_CLIENT_FILE
kubernetes.certs.client.data
/ KUBERNETES_CERTS_CLIENT_DATA
kubernetes.certs.client.key.file
/ KUBERNETES_CERTS_CLIENT_KEY_FILE
kubernetes.certs.client.key.data
/ KUBERNETES_CERTS_CLIENT_KEY_DATA
kubernetes.certs.client.key.algo
/ KUBERNETES_CERTS_CLIENT_KEY_ALGO
Client key encryption algorithm RSA
kubernetes.certs.client.key.passphrase
/ KUBERNETES_CERTS_CLIENT_KEY_PASSPHRASE
kubernetes.auth.basic.username
/ KUBERNETES_AUTH_BASIC_USERNAME
kubernetes.auth.basic.password
/ KUBERNETES_AUTH_BASIC_PASSWORD
kubernetes.auth.serviceAccount.token
/ KUBERNETES_AUTH_SERVICEACCOUNT_TOKEN
Name of the service account token file /var/run/secrets/kubernetes.io/serviceaccount/token
kubernetes.auth.tryKubeConfig
/ KUBERNETES_AUTH_TRYKUBECONFIG
Configure client using Kubernetes config true
kubeconfig
/ KUBECONFIG
Name of the kubernetes config file to read ~/.kube/config
kubernetes.auth.tryServiceAccount
/ KUBERNETES_AUTH_TRYSERVICEACCOUNT
Configure client from Service account true
kubernetes.tryNamespacePath
/ KUBERNETES_TRYNAMESPACEPATH
Configure client namespace from Kubernetes service account namespace path true
kubernetes.auth.token
/ KUBERNETES_AUTH_TOKEN
kubernetes.watch.reconnectInterval
/ KUBERNETES_WATCH_RECONNECTINTERVAL
Watch reconnect interval in ms 1000
kubernetes.watch.reconnectLimit
/ KUBERNETES_WATCH_RECONNECTLIMIT
Number of reconnect attempts (-1 for infinite) -1
kubernetes.connection.timeout
/ KUBERNETES_CONNECTION_TIMEOUT
Connection timeout in ms (0 for no timeout) 10000
kubernetes.request.timeout
/ KUBERNETES_REQUEST_TIMEOUT
Read timeout in ms 10000
kubernetes.upload.connection.timeout
/ KUBERNETES_UPLOAD_CONNECTION_TIMEOUT
Pod upload connection timeout in ms 10000
kubernetes.upload.request.timeout
/ KUBERNETES_UPLOAD_REQUEST_TIMEOUT
Pod upload request timeout in ms 120000
kubernetes.request.retry.backoffLimit
/ KUBERNETES_REQUEST_RETRY_BACKOFFLIMIT
Number of retry attempts (-1 for infinite) 10
kubernetes.request.retry.backoffInterval
/ KUBERNETES_REQUEST_RETRY_BACKOFFINTERVAL
Retry initial backoff interval in ms 100
kubernetes.rolling.timeout
/ KUBERNETES_ROLLING_TIMEOUT
Rolling timeout in ms 900000
kubernetes.logging.interval
/ KUBERNETES_LOGGING_INTERVAL
Logging interval in ms 20000
kubernetes.scale.timeout
/ KUBERNETES_SCALE_TIMEOUT
Scale timeout in ms 600000
kubernetes.websocket.timeout
/ KUBERNETES_WEBSOCKET_TIMEOUT
Websocket timeout in ms 5000
kubernetes.websocket.ping.interval
/ KUBERNETES_WEBSOCKET_PING_INTERVAL
Websocket ping interval in ms 30000
kubernetes.max.concurrent.requests
/ KUBERNETES_MAX_CONCURRENT_REQUESTS
64
kubernetes.max.concurrent.requests.per.host
/ KUBERNETES_MAX_CONCURRENT_REQUESTS_PER_HOST
5
kubernetes.impersonate.username
/ KUBERNETES_IMPERSONATE_USERNAME
Impersonate-User
HTTP header value kubernetes.impersonate.group
/ KUBERNETES_IMPERSONATE_GROUP
Impersonate-Group
HTTP header value kubernetes.tls.versions
/ KUBERNETES_TLS_VERSIONS
TLS versions separated by ,
TLSv1.2,TLSv1.3
kubernetes.truststore.file
/ KUBERNETES_TRUSTSTORE_FILE
kubernetes.truststore.passphrase
/ KUBERNETES_TRUSTSTORE_PASSPHRASE
kubernetes.keystore.file
/ KUBERNETES_KEYSTORE_FILE
kubernetes.keystore.passphrase
/ KUBERNETES_KEYSTORE_PASSPHRASE
kubernetes.backwardsCompatibilityInterceptor.disable
/ KUBERNETES_BACKWARDSCOMPATIBILITYINTERCEPTOR_DISABLE
Disable the BackwardsCompatibilityInterceptor
true
no.proxy
/ NO_PROXY
comma-separated list of domain extensions proxy should not be used for http.proxy
/ HTTP_PROXY
URL to the proxy for HTTP requests (See Proxy precedence) https.proxy
/ HTTPS_PROXY
URL to the proxy for HTTPS requests (See Proxy precedence)
Alternatively you can use the ConfigBuilder
to create a config object for the Kubernetes client:
Config config = new ConfigBuilder().withMasterUrl("https://mymaster.com").build(); KubernetesClient client = new KubernetesClientBuilder().withConfig(config).build();
Using the DSL is the same for all resources.
List resources:
NamespaceList myNs = client.namespaces().list(); ServiceList myServices = client.services().list(); ServiceList myNsServices = client.services().inNamespace("default").list();
Get a resource:
Namespace myns = client.namespaces().withName("myns").get(); Service myservice = client.services().inNamespace("default").withName("myservice").get();
Delete:
Namespace myns = client.namespaces().withName("myns").delete(); Service myservice = client.services().inNamespace("default").withName("myservice").delete();
Editing resources uses the inline builders from the Kubernetes Model:
Namespace myns = client.namespaces().withName("myns").edit(n -> new NamespaceBuilder(n) .editMetadata() .addToLabels("a", "label") .endMetadata() .build()); Service myservice = client.services().inNamespace("default").withName("myservice").edit(s -> new ServiceBuilder(s) .editMetadata() .addToLabels("another", "label") .endMetadata() .build());
In the same spirit you can inline builders to create:
Namespace myns = client.namespaces().create(new NamespaceBuilder() .withNewMetadata() .withName("myns") .addToLabels("a", "label") .endMetadata() .build()); Service myservice = client.services().inNamespace("default").create(new ServiceBuilder() .withNewMetadata() .withName("myservice") .addToLabels("another", "label") .endMetadata() .build());
You can also set the apiVersion of the resource like in the case of SecurityContextConstraints :
SecurityContextConstraints scc = new SecurityContextConstraintsBuilder() .withApiVersion("v1") .withNewMetadata().withName("scc").endMetadata() .withAllowPrivilegedContainer(true) .withNewRunAsUser() .withType("RunAsAny") .endRunAsUser() .build();
Use io.fabric8.kubernetes.api.model.Event
as T for Watcher:
client.events().inAnyNamespace().watch(new Watcher<>() { @Override public void eventReceived(Action action, Event resource) { System.out.println("event " + action.name() + " " + resource.toString()); } @Override public void onClose(WatcherException cause) { System.out.println("Watcher close due to " + cause); } });
The kubernetes API defines a bunch of extensions like daemonSets
, jobs
, ingresses
and so forth which are all usable in the extensions()
DSL:
e.g. to list the jobs...
jobs = client.batch().jobs().list();
Loading resources from external sources
There are cases where you want to read a resource from an external source, rather than defining it using the clients DSL. For those cases the client allows you to load the resource from:
Once the resource is loaded, you can treat it as you would, had you created it yourself.
For example lets read a pod, from a yml file and work with it:
Pod refreshed = client.load('/path/to/a/pod.yml').fromServer().get();
client.load('/workspace/pod.yml').delete();
LogWatch handle = client.load('/workspace/pod.yml').watchLog(System.out);
Passing a reference of a resource to the client
In the same spirit you can use an object created externally (either a reference or using its string representation).
For example:
Pod pod = someThirdPartyCodeThatCreatesAPod();
client.resource(pod).delete();
The client supports plug-able adapters. An example adapter is the OpenShift Adapter which allows adapting an existing KubernetesClient instance to an OpenShiftClient one.
For example:
KubernetesClient client = new KubernetesClientBuilder().build(); OpenShiftClient oClient = client.adapt(OpenShiftClient.class);
The client also support the isAdaptable() method which checks if the adaptation is possible and returns true if it does.
KubernetesClient client = new KubernetesClientBuilder().build(); if (client.isAdaptable(OpenShiftClient.class)) { OpenShiftClient oClient = client.adapt(OpenShiftClient.class); } else { throw new Exception("Adapting to OpenShiftClient not support. Check if adapter is present, and that env provides /oapi root path."); }
Note that when using adapt() both the adaptee and the target will share the same resources (underlying http client, thread pools etc). This means that close() is not required to be used on every single instance created via adapt. Calling close() on any of the adapt() managed instances or the original instance, will properly clean up all the resources and thus none of the instances will be usable any longer.
Along with the client this project also provides a Kubernetes Mock Server that you can use for testing purposes.
The Mock Web Server has two modes of operation:
In this mode, you can set up expectations for the server to respond to HTTP and websocket requests.
This mode has been extensively used for testing the client itself. Make sure you check kubernetes-test.
To add a Kubernetes server to your test:
@EnableKubernetesMockClient class MyTestSuite { KubernetesMockServer server; }
Then you can use the server to define the expectations and the client to perform the regular kubernetes operations:
class MyTestSuite { KubernetesMockServer server; KubernetesClient client; @Test void myTest() { server.expect().get() .withPath("/api/v1/namespaces/my-namespace/pods/my-pod") .andReturn(200, new PodBuilder().build()) .always(); Pod pod = client.pods().inNamespace("my-namespace").withName("my-pod").get(); } }
Defining every single request and response can become tiresome. Given that in most cases the Mock Server is mostly used to perform simple CRUD based operations, a CRUD mode is also available.
When using the CRUD mode, the mock web server will store, read, update and delete kubernetes resources using an in memory map and will appear as a real API server.
To add a Kubernetes Server in crud mode to your test:
@EnableKubernetesMockClient(crud = true) class MyTestSuite { KubernetesClient client; }
Then you can use the client to perform the regular kubernetes operations:
class MyTestSuite { KubernetesClient client; @Test public void myCrudTest() { //CREATE client.pods().inNamespace("ns1").create(new PodBuilder().withNewMetadata().withName("pod1").endMetadata().build()); //READ podList = client.pods().inNamespace("ns1").list(); assertNotNull(podList); assertEquals(1, podList.getItems().size()); } }Testing Against real Kubernetes API Server with Kube API Test
In order to test against real Kubernetes API the project provides a lightweight approach, thus starting up Kubernetes API Server and etcd binaries.
@EnableKubeAPIServer class KubeAPITestSample { static KubernetesClient client; @Test void testWithClient() { // test using the client against real K8S API Server } }
For details see docs for Kube API Test.
Starting from v5.5, the Kubernetes Client should be compatible with any supported Kubernetes cluster version. We provide DSL methods (for example client.pods()
, client.namespaces()
, and so on) for the most commonly used Kubernetes resources. If the resource you're looking for is not available through the DSL, you can always use the generic client.resource()
method to interact with it. You can also open a new issue to request the addition of a new resource to the DSL.
We provide Kubernetes Java model types (for example Pod
) and their corresponding builders (for example PodBuilder
) for every vanilla Kubernetes resource (and some extensions). If you don't find a specific resource, and you think that it should be part of the Kubernetes Client, please open a new issue.
Starting from v5.5, the OpenShift Client should be compatible with any OpenShift cluster version currently supported by Red Hat. The Fabric8 Kubernetes Client is one of the few Kubernetes Java clients that provides full support for any supported OpenShift cluster version. If you find any incompatibility or something missing, please open a new issue.
Major Changes in Kubernetes Client 4.0.0All the resource objects used here will be according to OpenShift 3.9.0 and Kubernetes 1.9.0. All the resource objects will give all the fields according to OpenShift 3.9.0 and Kubernetes 1.9.0
batch
and extensions
(Extensions is deprecated)apps
and extensions
(Extensions is deprecated)apps
and extensions
(Extensions is deprecated)apps
and extensions
(Extensions is deprecated)network
and extensions
(Extensions is deprecated)client base DSL
to storage
DSLclient base DSL
and extensions
to only extensions
Extensions:
Frameworks/Libraries/Tools:
CI Plugins:
Build Tools:
Platforms:
Proprietary Platforms:
As our community grows, we would like to track keep track of our users. Please send a PR with your organization/community name.
Tests we run for every new Pull RequestThere are the links of the Github Actions and Jenkins for the tests which run for every new Pull Request. You can view all the recent builds also.
To get the updates about the releases, you can join https://groups.google.com/forum/embed/?place=forum/fabric8-devclients
This table provides kubectl
to Kubernetes Java Client mappings. Most of the mappings are quite straightforward and are one liner operations. However, some might require slightly more code to achieve same result:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4