Search code examples
jenkinsjenkins-pipelinejenkins-groovy

Jenkins pipeline condition when not and regex


I'm trying to create a Jenkins pipeline and expect this task to work.

  • If a commit message doesn't contain the string "Built by Jenkins.*" then we run the building process.
  • If it contains the string "Built by Jenkins.*" we do nothing.

However, my regex doesn't work. May I have a mistake in the pipeline that I need help finding out?

pipeline {
  agent {
    node {
      label 'jenkins'
    }
  }
  environment {
    PATH = "/var/lib/jenkins/go/bin:/root/go/bin:/var/lib/jenkins/.gvm/bin/:${env.PATH}"
    BRANCH = "main"
    CREDSID = "jenk"
    GITURL = "git@..."
  }

    stages {
        stage('Clone and build') {
            steps {
                echo 'Cleaning'
                cleanWs()
                
                echo 'Start cloning GIT'
                checkout scmGit(branches: [[name: "*/${BRANCH}"]], extensions: [], userRemoteConfigs: [[credentialsId: "${CREDSID}", url: "${GITURL}"]])
                sh "git checkout ${BRANCH}"

                script {
                    def commitmsg = sh(script: 'git log -1 --pretty=%B', returnStdout: true).trim()
                    env.commitMessage = commitmsg
                    echo "${env.commitMessage}"
                }
            }
        }

        stage('Git Push To Origin') {
            when {
                not {
                    expression { env.commitMessage == "Built by Jenkins.*" }
                }
            }
            steps {
                sh 'make generate'
                withCredentials([gitUsernamePassword(credentialsId: 'jenki', gitToolName: 'git-tool')]) {
                    sh """
                        git add -A
                        git commit -m 'Built by Jenkins: ${BUILD_NUMBER} for ${env.commitMessage}'
                        git push
                    """
                }
            }
        }

        stage('No changes was made') {
            when {
                expression { env.commitMessage == "Built by Jenkins.*" }
            }
            steps {
                echo "Skipped because commit message contains \"Built by Jenkins\""
            }
        }
    }
}


Solution

  • The way you are evaluating your regex expression is wrong. Try one of the following ways to evaluate the expression.

    expression { env.commitMessage ==~ /^Built by Jenkins.*/ }
    
    expression { env.commitMessage.startsWith("Built by Jenkins") }
    
    expression { env.commitMessage.contains("Built by Jenkins") }