jenkins buildingTag()始终返回false

v8wbuo2f  于 2022-11-28  发布在  Jenkins
关注(0)|答案(4)|浏览(250)

每当我尝试使用buildingTag()创建条件阶段时,该阶段总是被跳过,即使当前提交是一个标记。

pipeline {
  agent {
    docker {
      image 'node:10'
    }

  }
  stages {
    stage('Build') {
      steps {
        sh 'yarn install'
        sh 'node scripts/build.js'
      }
    }
    stage('Lint') {
      steps {
        sh 'yarn lint'
      }
    }
    stage('Deploy') {
      when {
        buildingTag()
      }
      environment {
      }
      steps {
        sh 'node scripts/deploy.js'
        sh 'node scripts/publish.js'
      }
    }
  }
}
9rbhqvlz

9rbhqvlz1#

可能是由于此错误:
https://issues.jenkins-ci.org/browse/JENKINS-55987
解决方法是:

when {
                expression {
                    return !isVersionTag(readCurrentTag())           
                }
            }

与:

def boolean isVersionTag(String tag) {
    echo "checking version tag $tag"

    if (tag == null) {
        return false
    }

    // use your preferred pattern
    def tagMatcher = tag =~ /\d+\.\d+\.\d+/

    return tagMatcher.matches()
}

// workaround https://issues.jenkins-ci.org/browse/JENKINS-55987
def String readCurrentTag() {

    return sh(returnStdout: true, script: "git describe --tags").trim()           
}
mitkmikd

mitkmikd2#

buildingTag()要求设置TAG_NAME环境变量。
在简单(非多分支)管道中不会自动设置此值。

pipeline {
    agent any
    environment {
        // To get the tag like shown soru's answer:
        // TAG_NAME = sh(returnStdout: true, script: "git describe --tags").trim()

        // In my case I already have a tag saved as an environment variable:
        // gitlabBranch=refs/tags/tagname
        TAG_NAME = "${env.gitlabBranch.split('/')[2]}"
    }
    stages {
        stage('buildingTag') {
            when { buildingTag() }
            steps {
                echo 'buildingTag works here.'
            }
        }
    }
}
nlejzf6q

nlejzf6q3#

我也遇到了这个问题。你所需要做的就是在项目设置中启用Advanced clone behaviours -> Fetch tags,并在Jenkins文件中设置TAG_NAME环境变量。
1-高级克隆行为

2-提取标记

3-并在管道中设置TAG_NAME变量(buildingTag函数需要此变量)

pipeline {
  environment {
    TAG_NAME = sh(returnStdout: true, script: "git --no-pager tag --points-at HEAD").trim()
  }
  agent {
...

4-使用Jenkins的buildingTag函数检查commit是否有标记

...
  stage("Publish Release Artifact") {
    when {
      buildingTag()
    }
...
zf2sa74q

zf2sa74q4#

我一直在使用soru的解决方案,但是在构建一个带标签的分支时遇到了问题,所以我尝试了这个方法,它看起来很有效:

def boolean isVersionTag(String tag) {
    echo "checking version tag $tag"

    if (tag == null) {
        return false
    }

    // use your preferred pattern
    def tagMatcher = tag =~ /\d+\.\d+\.\d+/

    return tagMatcher.matches()
}

def String readCurrentTag() {
    return sh(returnStdout: true, script: 'echo ${TAG_NAME}').trim()
}

相关问题