记录一下,读取yaml文件中属性的值,这里用Kubernetes的deployment.yaml文件来举例。
读取yaml文件中的image的值
yaml文件
- apiVersion: apps/v1 # 1.9.0 之前的版本使用 apps/v1beta2,可通过命令 kubectl api-versions 查看
- kind: Deployment #指定创建资源的角色/类型
- metadata: #资源的元数据/属性
- name: nginx-deployment #资源的名字,在同一个namespace中必须唯一
- spec:
- replicas: 2 #副本数量2
- selector: #定义标签选择器
- matchLabels:
- app: web-server
- template: #这里Pod的定义
- metadata:
- labels: #Pod的label
- app: web-server
- spec: # 指定该资源的内容
- containers:
- - name: nginx #容器的名字
- image: nginx:1.12.1 #容器的镜像地址
- ports:
- - containerPort: 80 #容器对外的端口
读取文件的代码:
- package com.zhh.demo;
-
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONArray;
- import com.alibaba.fastjson.JSONObject;
- import org.junit.jupiter.api.Test;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.yaml.snakeyaml.Yaml;
-
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
-
- /**
- * @Description: yaml文件属性读取
- * @Author: zhaoheng
- */
- @SpringBootTest
- public class YamlTest {
-
- /**
- * 读取yaml文件中的image标签的值,文件中可以有多个image标签,最终得到一个数组
- * @param yamlPath 需要读取的yaml文件路径
- * @return 得到一个数组
- * @throws FileNotFoundException
- */
- public static List
getImageValues(String yamlPath) throws FileNotFoundException { - List
imageList = new ArrayList<>(); - Yaml yaml = new Yaml();
- Map map = yaml.load(new FileInputStream(new File(yamlPath)));
- // 把map对象转换成json对象,方便后续的层级读取
- JSONObject jsonObject = (JSONObject) JSON.toJSON(map);
- // 一层一层读取,同一层级可能有多个同样的标签,所以得到一个数组
- JSONArray jsonArray = jsonObject.getJSONObject("spec").getJSONObject("template").getJSONObject("spec").getJSONArray("containers");
- jsonArray.forEach(obj -> {
- // 获取image标签的值
- imageList.add(String.valueOf(((JSONObject) obj).get("image")));
- });
- return imageList;
- }
-
- @Test
- void yamlTest() throws FileNotFoundException {
- String path = "D:\\temp\\test.yaml";
- // 得到yaml文件中的image镜像的值
- List
list = YamlTest.getImageValues(path); - System.out.println(list.toString());
- }
-
- }
结果展示:
