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)