Jenkins高级篇之Pipeline方法篇-Pipeline Utility Steps-1-方法findFiles

释放双眼,带上耳机,听听看~!

       这篇开始,我逐渐来介绍Pipeline Utility Steps这个插件的一些常用的方法,这些方法就相当于我们使用jdk里面提供的方法。但是前提是在你的Jenkins环境上在管理插件这个地方,你需要搜索并安装Pipeline Utility Steps这个插件,如果没有安装就直接使用里面的方法,会发生错误,下面文章会具体介绍。

       为什么会先介绍Pipeline Utility Steps这个插件的方法,在https://jenkins.io/doc/pipeline/steps/页面有很多插件方法的如何在pipeline代码的使用介绍。我的短期内的工作经验和易学以及实用的角度来说,我先介绍Pipeline Utility Steps这个插件的方法。

方法 findFiles

       这个方法的作用是,在Jenins节点机器当前运行的工作目录下(通过WORKSPACE可以找到),根据一些字符串规则去查找文件,如果有匹配的查找,返回是一个fille数组对象。

       这个方法相关的还有一个可选指令glob,参数是字符串,字符串是根据ant 类型的模式去匹配查找文件,基本用法是def files = findFiles(glob: '**/*.log'),这样代码的含义就是找出当前workspace下的所有.log结尾的文件。

前提准备:

       由于我们是在jenkins上直接运行代码,没有走github方式拉取代码去构建,所有运行job不会自动在Jenkins node机器上创建当前这个jenkins job名称的文件夹路径。这里,你在你win或者linux Jenkins 节点机器上提前创建好文件夹,然后在这个文件夹下创建一些不同名称的.log文件,当然也可以创建其他类型文件。例如我的环境是linux。


1
2
3
4
5
6
7
8
9
10
11
12
1[root@Anthony workspace]# pwd
2/var/lib/jenkins/workspace
3[root@Anthony workspace]# ls
4mytest              paramater_job_demo@tmp    utilty_methods_demo
5mytest@tmp          Pipeline-learn-Demo1
6paramater_job_demo  Pipeline-learn-Demo1@tmp
7[root@Anthony workspace]# cd utilty_methods_demo/
8[root@Anthony utilty_methods_demo]# ls
9123.log  abc.log  dhi.txt
10[root@Anthony utilty_methods_demo]#
11
12

然后,在Jenkins环境下下,找到新建pipeline job,然,后把以下代码拷贝到脚本框里,点击保存,尝试Build now操作,看看报错是什么。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1pipeline {
2    agent any 
3    stages {
4        stage('Utility Steps method') {
5            steps {
6                script {
7                    def files = findFiles(glob: '**/*.log')
8                    echo files[0].name
9                    //echo files[1].name
10                }
11            }
12        }
13    }
14}
15
16

运行之后,应该会报错,报错大致内容如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
1[Pipeline] End of Pipeline
2java.lang.NoSuchMethodError: No such DSL method 'findFiles' found among steps
3[archive, bat, build, catchError, checkout, deleteDir, dir,
4dockerFingerprintFrom, dockerFingerprintRun, echo, emailext,
5emailextrecipients, envVarsForTool, error, fileExists, getContext,
6 git, input, isUnix, junit, library, libraryResource, load, lock,
7 mail, milestone, node, parallel, powershell, properties, pwd,
8readFile, readTrusted, resolveScm, retry, script, sh, sleep, stage,
9 stash, step, svn, timeout, timestamps, tm, tool, unarchive, unstash, validateDeclarativePipeline, waitUntil, withContext, withCredentials, withDockerContainer, withDockerRegistry, withDockerServer, withEnv,
10wrap, writeFile, ws] or symbols [all, allOf, always, ant, antFromApache,
11antOutcome, antTarget, any, anyOf, apiToken, architecture, archiveArtifacts, artifactManager, authorizationMatrix, batchFile, booleanParam, branch, brokenBuildSuspects, brokenTestsSuspects, buildButton, buildDiscarder,
12buildingTag, caseInsensitive, caseSensitive, certificate, changeRequest,
13changelog, changeset, checkoutToSubdirectory, choice, choiceParam, cleanWs,
14 clock, cloud, command, credentials, cron, crumb, culprits, defaultView,
15demand, developers, disableConcurrentBuilds, disableResume, docker,
16dockerCert, dockerfile, downloadSettings, downstream, dumb,
17durabilityHint, envVars, environment, equals, expression,
18file, fileParam, filePath, fingerprint, frameOptions,
19freeStyle, freeStyleJob, fromScm, fromSource, git,
20github, githubPush, gradle, headRegexFilter, headWildcardFilter,
21hyperlink, hyperlinkToModels, inheriting,
22inheritingGlobal, installSource, isRestartedRun,
23jdk, jdkInstaller, jgit, jgitapache, jnlp, jobName,
24label, lastDuration, lastFailure, lastGrantedAuthorities,
25 lastStable, lastSuccess, legacy, legacySCM, list,
26local, location, logRotator, loggedInUsersCanDoAnything,
27 masterBuild, maven, maven3Mojos, mavenErrors, mavenMojos,
28 mavenWarnings, modernSCM, myView, newContainerPerStage,
29node, nodeProperties, nonInheriting, nonStoredPasswordParam,
30 none, not, overrideIndexTriggers, paneStatus,
31parameters, password, pattern, permanent,
32pipeline-model, pipelineTriggers, plainText, plugin,
33pollSCM, preserveStashes, projectNamingStrategy, proxy,
34queueItemAuthenticator, quietPeriod, recipients, remotingCLI,
35requestor, run, runParam, schedule, scmRetryCount,
36scriptApprovalLink, search, security, shell, skipDefaultCheckout, skipStagesAfterUnstable, slave, sourceRegexFilter,
37sourceWildcardFilter, sshUserPrivateKey, stackTrace,
38standard, status, string, stringParam, swapSpace, tag,
39 text, textParam, tmpSpace, toolLocation, unsecured,
40upstream, upstreamDevelopers, usernameColonPassword,
41usernamePassword, viewsTabBar, weather, withAnt, zfs, zip]
42or globals [currentBuild, docker, env, params, pipeline, scm]
43  at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:201)
44  at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:122)
45
46

1
2
3
4
5
6
7
8
9
1这里,提醒这个报错“java.lang.NoSuchMethodError: No such DSL method 'findFiles' found among steps”,
2这个报错,错误的原因主要有两个,
3第一个你代码里调用的方法确实你自己写错了,
4例如那种低级失误,少了一个单词字母。
5第二种是,你确信存在这个方法,但是环境没有安装相关插件。
6第二种这种环境问题,就是本篇我们遇到的问题。
7所以你需需要去你Jenkins环境,插件管理页面,
8搜索并安装Pipeline Utility Steps这个插件。
9

Jenkins高级篇之Pipeline方法篇-Pipeline Utility Steps-1-方法findFiles


1
2
1因为我已经安装,但是你如果没有安装,你应该去Available这个tab下搜索。再次运行构建,日志大致如下。
2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
1Started by user admin
2Running in Durability level: MAX_SURVIVABILITY
3[Pipeline] node
4Running on Jenkins in /var/lib/jenkins/workspace/utilty_methods_demo
5[Pipeline] {
6[Pipeline] stage
7[Pipeline] { (Utility Steps method)
8[Pipeline] script
9[Pipeline] {
10[Pipeline] findFiles
11[Pipeline] echo
12123.log
13[Pipeline] }
14[Pipeline] // script
15[Pipeline] }
16[Pipeline] // stage
17[Pipeline] }
18[Pipeline] // node
19[Pipeline] End of Pipeline
20Finished: SUCCESS
21
22

1
2
1本篇,我们从findFiles方法学起,而且做的测试都是在Jenkins上修改代码,接下来我会慢慢转移到github上代码的方法,然后把方法模块化和jenkins pipeline代码文件进行分开。
2

 

 

 

给TA打赏
共{{data.count}}人
人已打赏
安全经验

职场中的那些话那些事

2021-9-24 20:41:29

安全经验

nginx 日志分析及性能排查

2021-11-28 16:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索