如何用Java调用OpenShift REST API及从YAML创建模板、配额等对象
嗨,我来帮你梳理清楚这两个OpenShift Java开发的常见问题!
一、用Java调用OpenShift REST API开展操作
OpenShift官方提供了封装好的Java客户端库,能让咱们不用手动写HTTP请求,就能轻松和REST API交互。
1. 先引入依赖
如果用Maven,直接把这个依赖加到你的pom.xml里:
<dependency> <groupId>io.fabric8</groupId> <artifactId>openshift-client</artifactId> <version>6.10.0</version> <!-- 建议用最新稳定版 --> </dependency>
Gradle项目对应调整依赖配置即可,这个客户端已经封装了所有OpenShift API的操作,省了很多重复造轮子的事。
2. 认证连接OpenShift集群
连接集群的核心是搞定认证,常见的两种方式:
方式一:Token认证(最常用,比如从oc login获取的token)
import io.fabric8.openshift.client.OpenShiftClient; import io.fabric8.openshift.client.OpenShiftClientBuilder; public class OpenShiftApiDemo { public static void main(String[] args) { String ocApiUrl = "https://your-openshift-cluster-api-url:6443"; String token = "your-auth-token"; // 创建客户端(用try-with-resources自动关闭连接) try (OpenShiftClient client = new OpenShiftClientBuilder() .withMasterUrl(ocApiUrl) .withOAuthToken(token) .build()) { // 验证连接是否成功,打印当前登录用户 System.out.println("当前登录用户:" + client.currentUser().getMetadata().getName()); } catch (Exception e) { e.printStackTrace(); } } }
方式二:用户名密码认证
try (OpenShiftClient client = new OpenShiftClientBuilder() .withMasterUrl(ocApiUrl) .withUsername("your-username") .withPassword("your-password") .build()) { // 后续操作逻辑... }
3. 常见操作示例
比如获取所有项目、创建Deployment、查看Pod状态:
// 获取所有项目列表 client.projects().list().getItems().forEach(project -> System.out.println("项目名称:" + project.getMetadata().getName()) ); // 创建一个简单的Nginx Deployment client.deployments() .inNamespace("your-namespace") .createOrReplaceWithNew() .withNewMetadata() .withName("demo-nginx-deployment") .endMetadata() .withNewSpec() .withReplicas(2) .withNewTemplate() .withNewSpec() .addNewContainer() .withName("nginx") .withImage("nginx:alpine") .endContainer() .endSpec() .endTemplate() .endSpec() .done();
二、通过Java读取YAML文件创建Template、Quota等OpenShift对象
完全可以!Fabric8客户端本身就支持从YAML字符串或文件加载OpenShift资源,配合Jackson的YAML解析器就能轻松实现。
1. 额外依赖(如果需要直接读取YAML文件)
如果你的项目还没引入Jackson YAML模块,要加这个:
<dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> <version>2.15.2</version> </dependency>
2. 读取YAML创建Template示例
假设你有一个demo-template.yaml文件,内容是OpenShift Template的定义:
apiVersion: template.openshift.io/v1 kind: Template metadata: name: demo-service-template objects: - apiVersion: v1 kind: Service metadata: name: ${SERVICE_NAME} spec: ports: - port: 8080 targetPort: 8080 selector: app: ${APP_NAME} parameters: - name: SERVICE_NAME value: demo-service - name: APP_NAME value: demo-app
然后用Java读取并创建:
import io.fabric8.openshift.api.model.Template; import java.io.File; public class YamlToOpenShiftObject { public static void main(String[] args) { String ocApiUrl = "https://your-openshift-cluster-api-url:6443"; String token = "your-auth-token"; try (OpenShiftClient client = new OpenShiftClientBuilder() .withMasterUrl(ocApiUrl) .withOAuthToken(token) .build()) { // 读取YAML文件并解析为Template对象 File templateFile = new File("path/to/demo-template.yaml"); Template template = client.templates().load(templateFile).get(); // 在指定namespace创建Template client.templates().inNamespace("your-namespace").createOrReplace(template); System.out.println("Template创建成功!"); } catch (Exception e) { e.printStackTrace(); } } }
3. 读取YAML创建Quota示例
Quota的操作逻辑和Template完全一致,只要你的YAML是Quota的定义:
apiVersion: v1 kind: ResourceQuota metadata: name: demo-resource-quota spec: hard: pods: "10" requests.cpu: "4" requests.memory: 8Gi limits.cpu: "8" limits.memory: 16Gi
对应的Java代码:
import io.fabric8.kubernetes.api.model.ResourceQuota; import java.io.File; // ... 连接客户端的代码省略 File quotaFile = new File("path/to/demo-quota.yaml"); ResourceQuota quota = client.resourceQuotas().load(quotaFile).get(); client.resourceQuotas().inNamespace("your-namespace").createOrReplace(quota);
小提示
- 如果YAML里有参数(比如Template的parameters),你可以在创建前用客户端的
process方法替换参数:Template processedTemplate = client.templates().process(template) .withParameter("SERVICE_NAME", "my-custom-service") .done(); client.templates().inNamespace("your-namespace").createOrReplace(processedTemplate); - 所有OpenShift资源(比如Route、BuildConfig等)都可以用这种方式从YAML加载创建,逻辑完全一致。
内容的提问来源于stack exchange,提问作者himanshu_mps
相关产品推荐
相关产品推荐

