这篇开始,我逐渐来介绍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。

[root@Anthony workspace]# pwd
/var/lib/jenkins/workspace
[root@Anthony workspace]# ls
mytest              paramater_job_demo@tmp    utilty_methods_demo
mytest@tmp          Pipeline-learn-Demo1
paramater_job_demo  Pipeline-learn-Demo1@tmp
[root@Anthony workspace]# cd utilty_methods_demo/
[root@Anthony utilty_methods_demo]# ls
123.log  abc.log  dhi.txt
[root@Anthony utilty_methods_demo]#

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

pipeline {
    agent any	
    stages {
        stage('Utility Steps method') {
            steps {
                script {
                    def files = findFiles(glob: '**/*.log')
                    echo files[0].name
                    //echo files[1].name
                }
            }
        }
    }
}

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

[Pipeline] End of Pipeline
java.lang.NoSuchMethodError: No such DSL method 'findFiles' found among steps 
[archive, bat, build, catchError, checkout, deleteDir, dir, 
dockerFingerprintFrom, dockerFingerprintRun, echo, emailext, 
emailextrecipients, envVarsForTool, error, fileExists, getContext,
 git, input, isUnix, junit, library, libraryResource, load, lock,
 mail, milestone, node, parallel, powershell, properties, pwd, 
readFile, readTrusted, resolveScm, retry, script, sh, sleep, stage,
 stash, step, svn, timeout, timestamps, tm, tool, unarchive, unstash, validateDeclarativePipeline, waitUntil, withContext, withCredentials, withDockerContainer, withDockerRegistry, withDockerServer, withEnv, 
wrap, writeFile, ws] or symbols [all, allOf, always, ant, antFromApache, 
antOutcome, antTarget, any, anyOf, apiToken, architecture, archiveArtifacts, artifactManager, authorizationMatrix, batchFile, booleanParam, branch, brokenBuildSuspects, brokenTestsSuspects, buildButton, buildDiscarder, 
buildingTag, caseInsensitive, caseSensitive, certificate, changeRequest, 
changelog, changeset, checkoutToSubdirectory, choice, choiceParam, cleanWs,
 clock, cloud, command, credentials, cron, crumb, culprits, defaultView, 
demand, developers, disableConcurrentBuilds, disableResume, docker,
dockerCert, dockerfile, downloadSettings, downstream, dumb, 
durabilityHint, envVars, environment, equals, expression, 
file, fileParam, filePath, fingerprint, frameOptions, 
freeStyle, freeStyleJob, fromScm, fromSource, git, 
github, githubPush, gradle, headRegexFilter, headWildcardFilter, 
hyperlink, hyperlinkToModels, inheriting, 
inheritingGlobal, installSource, isRestartedRun, 
jdk, jdkInstaller, jgit, jgitapache, jnlp, jobName, 
label, lastDuration, lastFailure, lastGrantedAuthorities,
 lastStable, lastSuccess, legacy, legacySCM, list, 
local, location, logRotator, loggedInUsersCanDoAnything,
 masterBuild, maven, maven3Mojos, mavenErrors, mavenMojos,
 mavenWarnings, modernSCM, myView, newContainerPerStage, 
node, nodeProperties, nonInheriting, nonStoredPasswordParam,
 none, not, overrideIndexTriggers, paneStatus, 
parameters, password, pattern, permanent, 
pipeline-model, pipelineTriggers, plainText, plugin, 
pollSCM, preserveStashes, projectNamingStrategy, proxy, 
queueItemAuthenticator, quietPeriod, recipients, remotingCLI, 
requestor, run, runParam, schedule, scmRetryCount, 
scriptApprovalLink, search, security, shell, skipDefaultCheckout, skipStagesAfterUnstable, slave, sourceRegexFilter, 
sourceWildcardFilter, sshUserPrivateKey, stackTrace, 
standard, status, string, stringParam, swapSpace, tag,
 text, textParam, tmpSpace, toolLocation, unsecured, 
upstream, upstreamDevelopers, usernameColonPassword, 
usernamePassword, viewsTabBar, weather, withAnt, zfs, zip]
or globals [currentBuild, docker, env, params, pipeline, scm]
	at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:201)
	at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:122)
这里,提醒这个报错“java.lang.NoSuchMethodError: No such DSL method 'findFiles' found among steps”,
这个报错,错误的原因主要有两个,
第一个你代码里调用的方法确实你自己写错了,
例如那种低级失误,少了一个单词字母。
第二种是,你确信存在这个方法,但是环境没有安装相关插件。
第二种这种环境问题,就是本篇我们遇到的问题。
所以你需需要去你Jenkins环境,插件管理页面,
搜索并安装Pipeline Utility Steps这个插件。

因为我已经安装,但是你如果没有安装,你应该去Available这个tab下搜索。再次运行构建,日志大致如下。
Started by user admin
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] node
Running on Jenkins in /var/lib/jenkins/workspace/utilty_methods_demo
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Utility Steps method)
[Pipeline] script
[Pipeline] {
[Pipeline] findFiles
[Pipeline] echo
123.log
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
本篇,我们从findFiles方法学起,而且做的测试都是在Jenkins上修改代码,接下来我会慢慢转移到github上代码的方法,然后把方法模块化和jenkins pipeline代码文件进行分开。

 

 

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐