1. 程式人生 > >Jenkins高階篇之Pipeline方法篇-Pipeline Utility Steps-1-方法findFiles

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陣列物件。

       這個方法相關的還有一個可選指令golb,引數是字串,字串是根據ant 型別的模式去匹配查詢檔案,基本用法是def files = findFiles(glob: '**/*.log'),這樣程式碼的含義就是找出當前workspace下的所有.log結尾的檔案。

前提準備:

       由於我們是在jenkins上直接執行程式碼,沒有走github方式拉取程式碼去構建,所有執行job不會自動在Jenkins node機器上建立當前這個jenkins job名稱的資料夾路徑。這裡,你在你win或者linux Jenkins 節點機器上提前建立好資料夾,然後在這個資料夾下建立一些不同名稱的.log檔案,當然也可以建立其他型別檔案。例如我的環境是linux。

[[email protected] workspace]# pwd
/var/lib/jenkins/workspace
[[email protected] workspace]# ls
mytest              [email protected]    utilty_methods_demo
[email protected]          Pipeline-learn-Demo1
paramater_job_demo  [email protected]
[[email protected] workspace]# cd utilty_methods_demo/
[
[email protected]
utilty_methods_demo]# ls 123.log abc.log dhi.txt [[email protected] 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程式碼檔案進行分開。