通过 Kubernetes Java Client API 操作Kubernetes Cluster

温翔宇
2023-12-01

Kubernete JAVA client offical link as below:

https://github.com/kubernetes-client/java

  • 按照README,先build java client,记得设置proxy,不然dependency下载会失败
git clone --recursive https://github.com/kubernetes-client/java
cd java
mvn install
  • 在IntelliJ IDEA中新建一个maven工程然后导入以下依赖
<dependency>
    <groupId>io.kubernetes</groupId>
    <artifactId>client-java</artifactId>
    <version>8.0.2</version>
    <scope>compile</scope>
</dependency>
private final String DEPLOYMENT_YAML = "test-deployments.yaml";

private String getPathFromResource(final String resourceName) 
{
                URL url = getClass().getClassLoader().getResource(resourceName);
                String filePath = null;
                if (url != null) {
                        filePath = url.toString().split(":")[1];
                }
                //assertNotNull(filePath);
                return filePath;
 }

public void CreateDeployment() throws IOException, ApiException, ClassNotFoundException
{
                //Read yaml configuration file, and deploy it
                ApiClient client = Config.defaultClient();
                Configuration.setDefaultApiClient(client);

                // Example yaml file can be found in $REPO_DIR/test-deployments.yaml
                File file = new File(getPathFromResource(DEPLOYMENT_YAML));
                V1Deployment yamlDeployment = (V1Deployment) Yaml.load(file);
                System.out.println(Yaml.dump(yamlDeployment));

                AppsV1Api api = new AppsV1Api();
                V1Deployment createResult = api.createNamespacedDeployment("default", yamlDeployment, null, null, null);
                System.out.println(createResult);
        }

 test-deployments.yaml文件的内容如下所示:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx:1.7.9
        name: nginx
        ports:
        - containerPort: 80

 

 类似资料: