实现Jenkinsfile与Json的转换

最近在做个需求,需要支持Jenkinsfile和json的转换。

方法1:使用现有的jenkins插件

参考的是这篇文章。下面介绍一下将插件打包成镜像的步骤:

  • 本地安装jdk和maven,jdk建议采用的版本为8(该工程会依赖一个名为tools.jar的包,jdk 9之后移除了该包)

    如果本地没有找到tools.jar,可以下载一个1.8版本的jdk,然后在pom.xml中增加如下依赖

    <dependency>
    <groupId>jdk.tools</groupId>
    <artifactId>jdk.tools</artifactId>
    <version>1.8.0</version>
    <scope>system</scope>
    <systemPath>/root/jdk1.8.0_271/lib/tools.jar</systemPath>
    </dependency>
  • clone pipeline-model-definition-plugin工程

  • 在/root/.m2/目录下创建settings.xml,内容来自Jenkins官方

    <settings>
    <pluginGroups>
    <pluginGroup>org.jenkins-ci.tools</pluginGroup>
    </pluginGroups> <profiles>
    <!-- Give access to Jenkins plugins -->
    <profile>
    <id>jenkins</id>
    <activation>
    <activeByDefault>true</activeByDefault> <!-- change this to false, if you don't like to have it on per default -->
    </activation>
    <repositories>
    <repository>
    <id>repo.jenkins-ci.org</id>
    <url>https://repo.jenkins-ci.org/public/</url>
    </repository>
    </repositories>
    <pluginRepositories>
    <pluginRepository>
    <id>repo.jenkins-ci.org</id>
    <url>https://repo.jenkins-ci.org/public/</url>
    </pluginRepository>
    </pluginRepositories>
    </profile>
    </profiles>
    <mirrors>
    <mirror>
    <id>repo.jenkins-ci.org</id>
    <url>https://repo.jenkins-ci.org/public/</url>
    <mirrorOf>m.g.o-public</mirrorOf>
    </mirror>
    </mirrors>
    </settings>
  • 执行 mvn install进行编译

  • 由于主要用到的是Jenkinsfile和json之间的转换关系,因此主要用的是如下两个REST API:

    • Conversion to JSON representation from Jenkinsfile

      • URL: JENKINS_URL/pipeline-model-converter/toJson
      • Parameters: jenkinsfile - the Jenkinsfile contents
      • Info: Takes a Jenkinsfile and converts it to the JSON representation for its pipeline step.
      • Returns: JSON with a result field that will either be success or failure. If success, the JSON representation will be in the json field. If failure, there'll be an additional array in the errors field of the error messages encountered.
    • Conversion to Jenkinsfile from JSON representation

      • URL: JENKINS_URL/pipeline-model-converter/toJenkinsfile
      • Parameters: json - the JSON representation of the model
      • Info: Takes the JSON representation of the model and converts it to the contents for a Jenkinsfile invoking the pipeline step.
      • Returns: JSON with a result field that will either be success or failure. If success, the Jenkinsfile contents will be in the jenkinsfile field. If failure, there'll be an additional array in the errors field of the error messages encountered.

    上述两个API在pipeline-model-definition-plugin/pipeline-model-definition目录下,因此在该目录下直接运行:mvn hpi:run -Dhost=0.0.0.0 -Djetty.port=8080即可。

  • 将json转换为Jenkinsfile的操作如下:

    完整的返回值如下:

    {
    "status": "ok",
    "data": {
    "result": "success",
    "json": {
    "pipeline": {
    "stages": [
    {
    "name": "Hello",
    "branches": [
    {
    "name": "default",
    "steps": [
    {
    "name": "echo",
    "arguments": [
    {
    "key": "message",
    "value": {
    "isLiteral": true,
    "value": "Hello World"
    }
    }
    ]
    }
    ]
    }
    ]
    }
    ],
    "agent": {
    "type": "any"
    }
    }
    }
    }
    }
  • 将Jenkinsfile转换为json的操作如下

  • 制作容器镜像时,只需要将本地工程和/root/.m2上传到容器,生成对应的镜像即可,下面Dockerfile假设生成的镜像为pipeline-model-definition-plugin:latest

    FROM pipeline-model-definition-plugin:latest
    WORKDIR /usr/pipeline-model-definition-plugin/pipeline-model-definition
    ENV PATH=$PATH:/usr/local/bin/maven-3.6.3/bin
    ENTRYPOINT ["sh", "-c", "mvn hpi:run -Dhost=0.0.0.0"]

    我自己打包了一个镜像:docker pull quay.io/woodliu/pipeline-model-definition-plugin

需要注意的是,本插件提供的转换API toJenkinsfile和toJson并不是万能的,只能支持jenkins标准的参数类型,例如对于gitParameter这样的参数就无法解析(扩展功能),一种解决方式是独立解析扩展的参数,然后将其插入解析好的标准JenkinsFile中;另外一个方式就是写一个jenkinsfile的解析器。

参考

  • mvn hpi的命令可以参考官方文档

  • 可以运行mvn hpi:hpi生成对应的hpi文件,如:

    /pipeline-model-definition-plugin/pipeline-model-definition/target/pipeline-model-definition.hpi

方法2:解析原生的jenkinsfile文件

在GitHub上有一个支持jenkinsfile解析的项目,该项目使用rust的pest crate来编写jenkinsfile的语法,支持对jenkinsfile的格式验证。Pest官方文档中给出了一个非常好的对json语法的解析例子,主要是使用递归的方式来解析语法。

pest官方提供了一个编辑器,可以使用该编辑器查看经过pest解析之后的字段,对了解pest的工作方式非常有用。如,使用jdp项目提供的pest文件解析如下jenkinsfile:

pipeline {
agent {
docker {
reuseNode true
image 'maven:3-alpine'
label 'my-defined-label'
args '-v /tmp:/tmp'
registryUrl 'https://myregistry.com/'
registryCredentialsId 'myPredefinedCredentialsInJenkins'
}
} stages {
stage('Build') {
steps { sh 'make' }
}
}
}

对应的解析结果如下:

- preceeding_junk: ""
- opening_brace: "{"
- agentDecl > agentBlock
- opening_brace: "{"
- dockerAgent
- opening_brace: "{"
- bool: "true"
- string > single_quoted
- single_quote: "\'"
- inner_single_str: "maven:3-alpine"
- single_quote: "\'"
- string > single_quoted
- single_quote: "\'"
- inner_single_str: "my-defined-label"
- single_quote: "\'"
- string > single_quoted
- single_quote: "\'"
- inner_single_str: "-v /tmp:/tmp"
- single_quote: "\'"
- string > single_quoted
- single_quote: "\'"
- inner_single_str: "https://myregistry.com/"
- single_quote: "\'"
- string > single_quoted
- single_quote: "\'"
- inner_single_str: "myPredefinedCredentialsInJenkins"
- single_quote: "\'"
- closing_brace: "}"
- closing_brace: "}"
- stagesDecl
- opening_brace: "{"
- stage
- string > single_quoted
- single_quote: "\'"
- inner_single_str: "Build"
- single_quote: "\'"
- opening_brace: "{"
- stepsDecl
- opening_brace: "{"
- step > simple_step
- IDENT: "sh"
- args > string > single_quoted
- single_quote: "\'"
- inner_single_str: "make"
- single_quote: "\'"
- closing_brace: "}"
- closing_brace: "}"
- closing_brace: "}"
- closing_brace: "}"
- ending_junk: ""
- EOI: ""

Pest语法重点标注:

  • 当使用静默规则时,解析结果中将不会出现该规则字段。当解析下面规则时,解析结果中将不会存在silent,即parsed.as_rule() 中不会存在silent

    silent = _{ ... }
  • 当使用原子语法时,整个规则体将视为一个规则,如double_quoted = ${ (quote ~ inner_double_str ~ quote) },在解析时会将quote ~ inner_double_str ~ quote视为一个规则,而不是三个。这有利于获取一段完整的字符串。

    atomic = @{ ... }
    compound_atomic = ${ ... }

我尝试使用该项目解析jenkinsfile,但发现实现起来太过复杂,且jenkinsFile的语法也是一言难尽。如下,当step中带括号和不带括号混用时会导致解析错误。

steps {
echo 'test'
dir('command') {
sh "sh ./saas.sh ${params.channel} ${params.buildType} "
}
}

有精力的大神可以在此基础上实现解析JenkinsFile的功能。

参考

jenkins:实现Jenkinsfile与Json的转换的更多相关文章

  1. Jenkinsfile与Json的转换

    前段时间调研了下青云的kubesphere,意外的发现了一个插件,pipeline-model-definition-plugin,用了将jenkins的pipeline.json互相转换的,以前可能 ...

  2. json日期转换

    //调用 ChangeDateFormat(CreatTime) //json日期转换 function ChangeDateFormat(jsondate) { jsondate = jsondat ...

  3. java中Array/List/Map/Object与Json互相转换详解

    http://blog.csdn.net/xiaomu709421487/article/details/51456705 JSON(JavaScript Object Notation): 是一种轻 ...

  4. Json格式转换

    验证Json格式可以进入 http://json.cn/ json简单说就是javascript中的对象和数组,所以这两种结构就是对象和数组两种结构,通过这两种结构可以表示各种复杂的结构1.对象:对象 ...

  5. JSON.stringify转换Date不正确的解決方法

    JSON.stringify转换Date不正确的原因:国际时区(UTC)和中国时区(GMT)的原因,东八区+8等于国际时区. 解决方法,重新Es5的Date.prototype.toJSON方法,代码 ...

  6. 使用js进行string和json之间转换的方法

    在数据传输过种中,json是以文本,即字符串的形式传递,字符串形似Json对象: var str1 = '{ "name": "Amy", "sex& ...

  7. 前台 JSON对象转换成字符串 相互转换 的几种方式

    在最近的工作中,使用到JSON进行数据的传递,特别是从前端传递到后台,前台可以直接采用ajax的data函数,按json格式传递,后台Request即可,但有的时候,需要传递多个参数,后台使用requ ...

  8. C#中服务端接受前端JSON字符串转换成字典集合

    我们是否可以把从前端接受的JSON字符串转换成字典集合呢? 比如从前端接收:{'size':'10', 'weight':'10kg'} 在服务端转换成:[{size:"10"}, ...

  9. json格式转换成Map的应用

    jsp 1.引用json.js(将json格式转换成字符串) 2. var name = document.getElementById("name").value; var re ...

随机推荐

  1. 【ASM】查看ASM磁盘组剩余容量和总容量

    col total_size for a10; col free_size for a20; select name,total_mb/1024 || 'G' as total_size , free ...

  2. 汇编学习笔记——DOS及DEBUG介绍

    转自:https://www.shiyanlou.com/courses/running/332 一.课程简介 声明:该课程基于<汇编语言(第2版)>郑晓薇 编著,机械工业出版社.本节实验 ...

  3. 被集群节点负载不均所困扰?TKE 重磅推出全链路调度解决方案

    引言 在 K8s 集群运营过程中,常常会被节点 CPU 和内存的高使用率所困扰,既影响了节点上 Pod 的稳定运行,也会增加节点故障的几率.为了应对集群节点高负载的问题,平衡各个节点之间的资源使用率, ...

  4. 学习Java第一天

    public 保证类名和文件名一致 关键字字母全小写,编辑器中有颜色标记 null空常量不能打印 变量就是内存中的存储空间 计算机中最小的存储单元时字节(byte) //1字节(B) = 8位(bit ...

  5. MATLAB中load和imread的读取方式区别

    load是导入文件,一般从mat文件中,读取的是结构体imread是图像处理工具箱的库函数,处理图像比较方便,读取的是矩阵 1.之前将数组或者矩阵保存为一个mat格式的文件,在进行load命令读取时: ...

  6. 精通MySQL之架构篇

    老刘是即将找工作的研究生,自学大数据开发,一路走来,感慨颇深,网上大数据的资料良莠不齐,于是想写一份详细的大数据开发指南.这份指南把大数据的[基础知识][框架分析][源码理解]都用自己的话描述出来,让 ...

  7. html新特性笔记

    HTML5知识总结 l  文档类型声明:<!DOCTYPE HTML> l  新绘制元素: Canvas:标签定义图形,比如图表和其他图像.该标签基于 JavaScript 的绘图 API ...

  8. SuperUpdate.sh 一键更换Linux软件源脚本

    一.前言 有时候会遇到 Linux 的源更新速度非常的缓慢,特别是在国内使用默认的源,因为国内的网络环境,经常会出现无法更新,更新缓慢的情况.在这种情况下,更换一个更适合或者说更近,更快的软件源,会为 ...

  9. https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError

    https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError

  10. GDB查看内存命令(x命令) 用gdb查看指定地址的内存内容

    GDB查看内存命令(x命令) - super119 - 博客园 https://www.cnblogs.com/super119/archive/2011/11/18/2254382.html 可以使 ...