Search code examples
mavenjenkinsjenkins-pipelinemultibranch-pipeline

Jenkins Multibranch Pipeline - mvn is not recognized as a command


I'd like to setup a simple Multibranch Pipeline for my Spring Boot project. I've created such a Multibranch Pipeline in Jenkins, wired in my GitHub repo where I've pushed a very basic Jenkinsfile with a simple step:

pipeline {
agent any
stages {
    stage('Build with unit testing') {
        steps {
            bat 'mvn clean package'
        }
    }
}
}

However Jenkins doesn't seem to understand the mvn command, because I get the following message in my build:

'mvn' is not recognized as an internal or external command, operable program or batch file.

In went to the Global Tool Configuration where I tried to specify a Maven installation, but regardless of what I do this configuration doesn't seem to persist (I add my Maven, click Apply/Save, go out and come back to this screen again, and the Maven section is empty again, displaying only the "Maven installations..." button. I guess this is the issue. I've read somewhere that this is a Jenkins bug? But could really decode the solution regarding how to solve this in my Jenkinsfile).

Do you guys have any tips how to overcome this problem?

Thanks!


Solution

  • According to the official jenkins docs, you need to declare maven in tools section:

    pipeline {
        agent any
        tools {
            maven 'Maven 3.3.9'
            jdk 'jdk8'
        }
        stages {
            stage ('Initialize') {
                steps {
                    sh '''
                        echo "PATH = ${PATH}"
                        echo "M2_HOME = ${M2_HOME}"
                    '''
                }
            }
    
            stage ('Build') {
                steps {
                    sh 'mvn clean package' 
                }
                post {
                    success {
                        junit 'target/surefire-reports/**/*.xml' 
                    }
                }
            }
        }
    }
    

    Source: https://www.jenkins.io/blog/2017/02/07/declarative-maven-project/

    I think your are in windows, so change:

    sh 'mvn clean package' 
    

    to

    bat 'mvn clean package' 
    

    Also the initialize step could help you to determine if your jenkins is properly configured.