Jenkinsfile get current tag

后端 未结 8 2173
南笙
南笙 2021-02-05 10:15

Is there a way to get the current tag ( or null if there is none ) for a job in a Jenkinsfile? The background is that I only want to build some artifacts ( android APKs ) when t

8条回答
  •  遇见更好的自我
    2021-02-05 10:34

    An example of declarative pipeline following the OP usecase: "do something if this particular commit has a tag attached":

    def gitTag = null
    pipeline {
      agent any
      stages {
        stage('Checkout') {
          steps {
            checkout(...)
            script {
              gitTag=sh(returnStdout: true, script: "git tag --contains | head -1").trim()
            }
          }
        }
        stage('If tagged') {
          when {
            expression {
              return gitTag;
            }
          }
          steps {
            // ... do something only if there's a tag on this particular commit
          }
        }
      }
    }
    

    In my case, I have:

    • one repository for multiple projects
    • each one with their own version tags such as 'MYPROJECT_1.4.23'
    • and I want to use the second part of the tag '1.4.23' to tag my images for example

    I need to analyze the current tag to check if it concerns my pipeline project (using a PROJECT_NAME variable per project):

    def gitTag = null
    def gitTagVersion = null
    pipeline {
      agent any
      stages {
        stage('Checkout') {
          steps {
            checkout(...)
            script {
              gitTag=sh(returnStdout: true, script: "git tag --contains | head -1").trim()
              if(gitTag) {
                def parts = gitTag.split('_')
                if( parts.size()==2 && parts[0]==PROJECT_NAME ) {
                  gitTagVersion=parts[1]
                }
              }
            }
          }
        }
        stage('If tagged') {
          when {
            expression {
              return gitTagVersion;
            }
          }
          steps {
            // ... do something only if there's a tag for this project on this particular commit
          }
        }
      }
    }
    

    Note that I'm new at Jenkins and Groovy and that this may be written more simply/cleanly (suggestions welcome).

    (with Jenkins 2.268)

提交回复
热议问题