CentOS搭建jenkins(2)—从gitlab拉取

1、配置jdk、maven、git全局参数
Jenkins – 系统管理 – 全局工具配置
1)Maven 配置
默认 settings 提供:使用默认Maven设置
默认全局 settings 提供:使用默认Maven全局设置
2)JDK
别名:openjdk
JAVA_HOME:/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.262.b10-0.el7_8.x86_64

3)Git
Name:git
Path to Git executable:/usr/bin/git

4)Maven
Name:maven
MAVEN_HOME:/usr/share/maven

2、配置远程部署
1)安装Publish Over SSH插件
2)Jenkins – 系统管理 – 系统配置 – Publish over SSH
新增SSH Server
Name:tomcat
Hostname:192.168.100.2
Username:root
Remote Directory:/home
选择Use password authentication, or use a different key
Passphrase / Password:123456
Port:22

3、配置gitlab信息
1)首先在gitlab上创建token
Settings – Developer settings – Personal access tokens
选择Generate new token,生成token
2)Jenkins – 系统管理 – 系统配置 – GitHub
设置GitHub Server
名称:github
API URL:https://api.github.com
添加凭据,选择Sercert text
填入gitlab生成的token

4、建立一个新的任务webapp
工作区路径:/var/lib/jenkins/workspace/
jenkins会在该目录下建立webapp目录,把代码拉到这个目录下编译
PS:
maven本地仓库路径:/var/lib/jenkins/.m2/repository/
1)源码管理
选择Git
Repository URL:https://github.com/xxx/webapp2
Credentials:******
指定分支(为空时代表any):*/master

2)构建环境
勾选Delete workspace before build starts
设置每次构建时清理工作区,重新拉代码
3)构建
增加构建步骤:执行shell
echo "********************compile and package start********************"
cd ./webapp2
mvn clean install -U -Dmaven.test.skip=true
echo "********************compile and package end********************"

4)构建后操作
增加构建后操作步骤:Send build artifacts over SSH
勾选Verbose output in console
Name:tomcat
Source files:webapp2/webapp2_web/target/webapp2.war
Remove prefix:webapp2/webapp2_web/target
Remote directory:/upload
Exec command:
#!/bin/sh
export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.262.b10-0.el7_8.x86_64
kill -9 $(ps -aef | grep tomcat | grep -v grep | awk '{print $2}')
cd /appserver/apache-tomcat-8.5.59/webapps/
mv webapp2.war webapp2_`date +%Y%m%d%H%M%S`.war.bak
rm -rf webapp2
mv /home/upload/webapp2.war webapp2.war
cd /appserver/apache-tomcat-8.5.59/bin
./startup.sh

5、说明
1)Source files是相对于工作区的路径
比如这里工作区路径是/var/lib/jenkins/workspace/webapp,编译后的war包在webapp2/webapp2_web/target/webapp2.war下
2)Remove prefix是上传时要去除的目录
否则jenkins会在tomcat远程目录建立webapp2/webapp2_web/target
3)Remote directory远程目录
实际的远程目录,是设置远程服务时指定的一级目录/home,加上这里的/upload,再加上源文件的路径,既上传到/home/upload/webapp2.war