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

qybjjes1  于 2023-08-01  发布在  Git
关注(0)|答案(1)|浏览(145)

如何让Jenkins从Jenkinsfile中的命令生成的控制台输出中提取值?
具体来说,我如何让Jenkins从下面这个非常简单的Jenkinsfile中的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日志在上面简化的Jenkinsfile中运行checkout scm命令后打印以下内容:

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

重复提问:

具体来说,我们要向Jenkinsfile添加什么,以便日志在结尾处额外打印出以下内容:

Commit hash is:  77cf12f42136efc77fecbcd1f761a54254278cb3


这显然过于简化了。在真实的生活中,打印输出将进入变量,并作为参数传递到脚本中。但是对于这个问题,什么特定的语法将使Jenkins能够提取提交哈希?

jogvjijk

jogvjijk1#

如果你特别需要commit hash,checkout步骤的文档提到了一个简单的方法来获得它(而不是解析控制台输出等):
这一步返回SCM插件在Freestyle作业中设置的任何变量的Map,所以如果你的SCM是git,你可以这样做:

def scmVars = checkout scm
    def commitHash = scmVars.GIT_COMMIT

    // or

    def commitHash = checkout(scm).GIT_COMMIT

字符串
一旦你把它放在一个变量中,你只需要回显它就可以在日志中看到它。

echo "Commit hash is: ${commitHash}"

相关问题