[Resolved] Jenkins - mvn: command not found

在Linux中使用Jenkins时, 在jenkinsFile中添加了sh 'mvn --version'命令,但Jenkins在build时报错如下:

> git rev-list --no-walk 75df912a72c7971f61d5c48b80b05bdc1243f86d # timeout=10
[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (build)
[Pipeline] sh
+ mvn --version
/var/lib/jenkins/workspace/SpringbootDeployment_master@tmp/durable-65e0b685/script.sh: line 1: mvn: command not found
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline

GitHub has been notified of this commit’s build result

ERROR: script returned exit code 127
Finished: FAILURE

仔细查了一下, 发现了问题的原因. 我对于java或maven的路径的环境变量是放在/etc/profile中的, 而/etc/profile只有在用户登录的时候才会被load,Jenkins在运行命令时,使用的是Non-login的方式,而这种方式在运行命令时,/etc/profile是不会被load进来的,所以jenkins只能在当前路径下寻找可执行文件.

解决方式:
在Jenkins的设置中可以设置全局变量, jenkins主页面->Manage Jenkins->Configure System->Global Properties 中, 将Environment variables复选框选中,会出来List of variables, 填入以下内容:

  • name: JAVA_HOME value:XXX
  • name: M2_HOME value:/usr/cyz/apache-maven-3.6.1
  • name: PATH+EXTRA value: $M2_HOME/bin

注意最后标红的 PATH+EXTRA, 这表示PATH=EXTRA:$PATH, 即扩展当前的PATH变量.
设置之后build成功.

你可能感兴趣的:(jenkins)