Jenkinsfile如何从控制台输出中提取值?

时间:2018-04-30 22:55:40

标签: git jenkins continuous-integration jenkins-pipeline

  

如何让Jenkins从Jenkinsfile中的命令生成的控制台输出中提取值?

     

具体来说,如何让Jenkins从以下非常简单的Jenkins文件中checkout scm命令的结果中提取提交哈希?

<小时/>的 Jenkinsfile <小时/>

node {
    // Clean workspace before doing anything
    deleteDir()
    try {
        stage ('Clone') {
            checkout scm    
        }
    } catch (err) {
        currentBuild.result = 'FAILED'
        throw err
    }
}  


输出checkout scm命令:

在上面简化的Jenkins文件中运行checkout scm命令后,Jenkins日志会打印以下内容:

Cloning the remote Git repository
Cloning with configured refspecs honoured and without tags
Cloning repository http://<bitbucket-ip-on-lan>:7990/scm/JSP/jenkinsfile-simple-repo.git
 > git init /var/jenkins_home/workspace/le-repo_sample-issue-branch-2WOFDGRDQWR367VAM7O26H2DKPTRVPDKRTGNRIS4AQNNFP7QIX2Q # timeout=10
Fetching upstream changes from http://<bitbucket-ip-on-lan>:7990/scm/JSP/jenkinsfile-simple-repo.git  
 > git --version # timeout=10  
 using GIT_ASKPASS to set credentials 
 > git fetch --no-tags --progress http://<bitbucket-ip-on-lan>:7990/scm/JSP/jenkinsfile-simple-repo.git +refs/heads/sample-issue-branch:refs/remotes/origin/sample-issue-branch
 > git config remote.origin.url http://<bitbucket-ip-on-lan>:7990/scm/JSP/jenkinsfile-simple-repo.git # timeout=10
 > git config --add remote.origin.fetch +refs/heads/sample-issue-branch:refs/remotes/origin/sample-issue-branch # timeout=10
 > git config remote.origin.url http://<bitbucket-ip-on-lan>:7990/scm/JSP/jenkinsfile-simple-repo.git # timeout=10
Fetching without tags
Fetching upstream changes from http://<bitbucket-ip-on-lan>:7990/scm/JSP/jenkinsfile-simple-repo.git  
using GIT_ASKPASS to set credentials 
 > git fetch --no-tags --progress http://<bitbucket-ip-on-lan>:7990/scm/JSP/jenkinsfile-simple-repo.git +refs/heads/sample-issue-branch:refs/remotes/origin/sample-issue-branch
Checking out Revision 77cf12f42136efc77fecbcd1f761a54254278cb3 (sample-issue-branch)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f 77cf12f42136efc77fecbcd1f761a54254278cb3
Commit message: "add whitespace"
 > git rev-list --no-walk e975fb4391677bc09f2056b3e8a6be62eda0b222 # timeout=10
[Bitbucket] Notifying commit build result


重申问题:

  

具体来说,我们将什么添加到Jenkins文件中,以便日志在最后另外打印出以下内容:

Commit hash is:  77cf12f42136efc77fecbcd1f761a54254278cb3  

这显然过于简化了。现实生活中的打印输出将进入变量并作为参数传递到脚本中。但是对于这个OP,具体的语法将使Jenkins能够提取提交哈希值吗?

1 个答案:

答案 0 :(得分:1)

如果你需要特别提交哈希,结账步骤的documentation提到了一种简单的方法来获取它(而不是解析控制台输出等):

  

此步骤返回SCM插件将在a中设置的任何变量的Map   自由式工作,所以如果你的SCM是git,你可以这样做:

    def scmVars = checkout scm
    def commitHash = scmVars.GIT_COMMIT

    // or

    def commitHash = checkout(scm).GIT_COMMIT

一旦你在一个变量中拥有它,只需回应它就可以在日志中看到它。

echo "Commit hash is: ${commitHash}"