[转] Jenkins pipeline 踩坑集合

2023-06-09,,

[From] https://testerhome.com/topics/10328

前言

最近由于项目需要,接触到了Jenkins 2.0版本,其中最重要的特性就是提供了对pipeline的支持。
简单的来说,就是把Jenkins1.0版本中,Project中的相关配置信息,如SVN/Git的配置,Parameter的配置等都变成Code,即Pipeline as Code。
这样的优势为可以通过写代码的形式配置Project,且Jenkins中内置了常用的steps。实现了构建步骤代码化、构建过程视图化。
其他的Jenkins基础这里不多说了,这里主要介绍最近遇到的问题及其处理方法。一方面是自己总结和整理一下,另一方面也可以供他人参考,少踩坑。

选择Declarative Pipeline还是Scripted Pipeline

最开始的Pipeline plugin,支持的只有一种脚本类型,就是Scripted Pipeline;
Declarative Pipeline为Pipeline plugin在2.5版本之后新增的一种脚本类型,与原先的Scripted Pipeline一样,都可以用来编写脚本。

使用哪一种脚本格式呢,我又纠结了,也查询了些资料。
https://stackoverflow.com/questions/43484979/jenkins-scripted-pipeline-or-declarative-pipeline
http://jenkins-ci.361315.n4.nabble.com/Declarative-pipelines-vs-scripted-td4891792.html

最后,我还是选择了Declarative Pipeline,这也是后续Open Blue Ocean所支持的类型。
相对而言,Declarative Pipeline比较简单,如果Groovy很熟的,用Scripted Pipeline可能更顺手。
另外,Declarative Pipeline中,是可以内嵌Scripted Pipeline代码的。

设置和获取执行参数

原先在Jenkins 1.0的时候,常用的一个设置就是“ "This build is parameterized",通过获取参数值,执行后续相关的判断及操作。
在pipeline中,可以这样设置:

#!/usr/bin/env groovy
pipeline{
agent none
options{
disableConcurrentBuilds()
skipDefaultCheckout()
timeout(time: , unit: 'HOURS')
timestamps()
}
parameters{
string(name: 'PERSON', defaultValue: 'among中文', description: '请输入中文')
booleanParam(name: 'YESORNO', defaultValue: true, description: '是否发布')
}
stages{
stage('test stage')
{
agent
{
label 'master'
}
steps
{
echo 'Hello, stage1'
echo "Hello ${params.PERSON}"
echo "Hello ${env.PERSON}"
scrip
{
def input = params.YESORNO
if (input)
{
echo "you input is ${input},to do sth"
}
else
{
echo "you input is ${input},nothing to do"
}
}
}
}
}

环境变量的问题

通过Jenkins 执行相关sh的时候,环境变量中,不会默认继承/etc/profile 和 ~/.profile 等环境变量。
这个时候就很麻烦了,尤其在一些依赖环境变量操作的sh脚本时。

可以这样来做,一是在增加node节点时,自己设置环境变量,如:

 

也可以在代码中这么写。写 withEnv ,或是直接在shell中先source profile文件。然后在执行相关命令。

steps
{
withEnv(['TPS=amtps']) {
// do sth
}
//
sh 'source /etc/profile && source ~/.bash_profile && env'
dir('/root')
{
sh '(source /etc/profile;source ~/.bash_profile;sh ./ee.sh)'
}
}

Jenkins中nohup后进程还是起不来的问题

在普通的shell环境中,nohup,并且& 某个程序后,会抛到后台执行,在退出当前shell环境后,程序依然可以执行。
但是在Jenkins中,通过nohup,且使用&之后,step结束后,执行的程序还是会退出,导致程序起不来。

尝试和验证了很多方法,后面都是这样解决的。
修改JENKINS_NODE_COOKIE的值,这样后续结束的时候,后面的sh程序就不会被kill掉了。
适用版本:Jenkins 2.46版本,版本如差异较大,可能不一致。当时为了解决这个问题,折腾了很久,找的资料也比较老了,很多都没用,特定记录一下。

steps
{
sh 'JENKINS_NODE_COOKIE=dontKillMe nohup python3 /home/among/pj/my_py/monitor/amon/amon.py >/tmp/run.log 2>&1 &'
}

shell出错后继续,取shell输出值。

这2个比较简单,看例子就知道了。

steps
{
sh returnStatus: true, script: "ps -ef|grep amon|grep -v grep|awk '{print \$2}'|xargs kill -9"
script
{
def pid = sh returnStdout: true ,script: "ps -ef|grep amon|grep -v grep|awk '{print \$2}'"
pid = pid.trim()
echo "you input pid is ${pid},to do sth"
sh "kill -9 ${pid}"
} }

以上就是最近遇到的一些问题,后续遇到了,我再补充吧。
一些地方有可能存在问题或有更好的解决方法,欢迎大家提出和完善。

[转] Jenkins pipeline 踩坑集合的相关教程结束。

《[转] Jenkins pipeline 踩坑集合.doc》

下载本文的Word格式文档,以方便收藏与打印。