Skip to content

Instantly share code, notes, and snippets.

@aespinosa
Created February 12, 2021 03:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aespinosa/10268e7dfc3b2b3661b0daea8e7269ee to your computer and use it in GitHub Desktop.
Save aespinosa/10268e7dfc3b2b3661b0daea8e7269ee to your computer and use it in GitHub Desktop.
Integration testing with the Kubernetes Java Client
// Start a Kubernetes Cluster. For building a controller we don't really
// need to have worker nodes. The control plane should be plenty.
// k3s server gives much more than that the controller-runtime test suite
// provides (no controller-manager and scheduler)
Path tempDir = Files.createTempDirectory("kube-cluster");
File kubeConfig = new File(tempDir.toFile(), "k3s.yaml");
Process k3sServer = new ProcessBuilder("k3s", "server", "--disable-agent",
"--bind-address", "127.0.0.1",
"--data-dir", tempDir.toString(),
"--write-kubeconfig", kubeConfig.toString())
.start();
// k3s server generates a KUBECONFIG file for the admin account. Wait until
// this file is available
while (true) {
if (kubeConfig.exists()) break;
Thread.sleep(500);
}
KubeConfig config = KubeConfig.loadKubeConfig(new FileReader(kubeConfig));
ApiClient admin = ClientBuilder.kubeconfig(config)
.build();
admin.setDebugging(true);
// Wait until the apiserver is actually ready.
while (true) {
int code = admin.buildCall("/readyz", "GET",
null, null, null, Map.of(), Map.of(), null,
new String[]{"BearerToken"}, null)
.execute().code();
if (code == 200) break;
Thread.sleep(500);
}
CoreV1Api core = new CoreV1Api(admin);
V1NamespaceList namespaces = core.listNamespace(null, null, null, null, null,
null, null, null, null, null);
System.out.println(namespaces);
// Wait for the k3s server to finish
k3sServer.destroy();
FileUtils.deleteDirectory(tempDir.toFile());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment