之前部署过jenkins(旧的文章),之前是因为jdk想要用8版本的所以用了旧版的jenkins,之前的文章写过了旧版jenkins是存在漏洞的,正好要部署新的jenkins,所以带来这篇文章来部署最新的jenkins来编译maven项目。
用独立的jenkins用户安装jenkins,用war包部署的方式
小团队推荐的硬件配置:4 GB+ 内存,50 GB 以上的驱动器空间
war包版本:2.387.1LTS(这个是20230314最新的LTS版本)
需要jdk11或者17(这两个版本是LTS版本,jdk版本要求)
已经安装了gitlab,从私有的gitlab拉取代码进行编译
gitlab上的代码需要使用jdk8来进行编译
然后通过ansible进行部署
下载版本包
useradd jenkins
passwd jenkins
su - jenkins
上传jenkins.war
安装jdk
上传jdk-17_linux-x64_bin.tar.gz
tar -zxf jdk-17_linux-x64_bin.tar.gz
rm -f jdk-17_linux-x64_bin.tar.gz
chown -R jenkins:jenkins /home/jenkins/jdk-17.0.6/
vi ~/.bash_profile
export JAVA_HOME=/home/jenkins/jdk-17.0.6
export PATH=$HOME/bin:$JAVA_HOME/bin:$PATH
source ~/.bash_profile
java -version
创建文件夹
mkdir /home/jenkins/jenkins_logs
mkdir /home/jenkins/jenkins_data
使用命令安装字体
yum install fontconfig
fc-cache --force
(下面是如果不安装字体会报的错)
java.lang.NullPointerException: Cannot load from short array because "sun.awt.FontConfiguration.head" is null
at java.desktop/sun.awt.FontConfiguration.getVersion(FontConfiguration.java:1262)
at java.desktop/sun.awt.FontConfiguration.readFontConfigFile(FontConfiguration.java:224)
at java.desktop/sun.awt.FontConfiguration.init(FontConfiguration.java:106)
添加jenkins家目录环境变量
vi ~/.bash_profile
export JENKINS_HOME=/home/jenkins/jenkins_data
source ~/.bash_profile
vi jenkins.sh
#!/bin/bash
# 在执行过程中若遇到使用了未定义的变量或命令返回值为非零,将直接报错退出
set -eu
# 检查参数个数
if [ "${#}" -lt 1 ]; then
echo "\033[41;37m 脚本使用示例: sh jenkins.sh start|stop|restart \033[0m"
exit
fi
# 获取脚本第一个参数
APP_OPT=${1}
# 端口
APP_PORT=8080
# 名称
APP_NAME=jenkins-2.387.1LTS.war
# jar名 | war名
APP_JAR=jenkins-2.387.1LTS.war
# 程序根目录
APP_JAR_HOME=/home/jenkins
# 日志名
APP_LOG_NAME=jenkins
# 日志根目录
APP_LOG_HOME=/home/jenkins/jenkins_logs
# 程序运行参数
JAVA_OPTS=" --httpPort=${APP_PORT} --prefix=/jenkins"
#--ajp13Port=-1
echo "本次操作服务名:[${APP_NAME}]"
echo "本次操作选择:[${APP_OPT}]"
# 停止
function stop(){
echo "<-------------------------------------->"
echo "[${APP_NAME}] ... stop ..."
# 查看该jar进程
pid=`ps -ef | grep ${APP_JAR} | grep -v 'grep' | awk '{print $2}'`
echo "[${APP_NAME}] pid="${pid}
# 存在则kill,不存在打印一下吧
if [ "${pid}" ]; then
kill -9 ${pid}
# 检查kill是否成功
if [ "$?" -eq 0 ]; then
echo "[${APP_NAME}] stop success"
else
echo "[${APP_NAME}] stop fail"
fi
else
echo "[${APP_NAME}] 进程不存在"
fi
}
# 运行
function start(){
echo "<-------------------------------------->"
echo "[${APP_NAME}] ... start ..."
cd ${APP_JAR_HOME}
echo "当前路径:`pwd`"
# 赋予可读可写可执行权限
chmod 777 ${APP_JAR}
echo "启动命令: nohup java -jar ${APP_JAR} ${JAVA_OPTS} >> ${APP_LOG_HOME}/${APP_NAME}.log 2>&1 &"
nohup java -jar ${APP_JAR} ${JAVA_OPTS} >> ${APP_LOG_HOME}/${APP_NAME}.log 2>&1 &
if [ "$?" -eq 0 ]; then
echo "[${APP_NAME}] start success"
else
echo "[${APP_NAME}] start fail"
fi
}
# 重启
function restart(){
echo "<-------------------------------------->"
echo "[${APP_NAME}] ... restart ..."
stop
start
}
# 多分支条件判断执行参数
case "${APP_OPT}" in
"stop")
stop
;;
"start")
start
;;
"restart")
restart
;;
*)
echo "\033[41;37m 提示:不支持参数 命令 -> ${APP_OPT} \033[0m"
;;
esac
启动一次,这次启动为了让jenkins创建出初始文件
sh jenkins.sh start
本次操作服务名:[jenkins-2.387.1LTS]
本次操作选择:[start]
<-------------------------------------->
[jenkins-2.387.1LTS] ... start ...
当前路径:/home/jenkins
启动命令: nohup java -jar jenkins-2.387.1LTS.war --httpPort=8080 --prefix=/jenkins >> /home/jenkins/jenkins_logs/jenkins-2.387.1LTS.log 2>&1 &
[jenkins-2.387.1LTS] start success
查看日志
vi /home/jenkins/jenkins_logs/jenkins-2.387.1LTS.log
最下面会有此提示信息证明成功
*************************************************************
*************************************************************
*************************************************************
Jenkins initial setup is required. An admin user has been created and a password g
enerated.
Please use the following password to proceed to installation:
4215bf0dc5b5459382e5bd0fdbc0e403
This may also be found at: /home/jenkins/jenkins_data/secrets/initialAdminPassword
*************************************************************
*************************************************************
*************************************************************
看日志成功关掉进程,去设置插件更新地址
sh jenkins.sh stop
本次操作服务名:[jenkins-2.387.1LTS]
本次操作选择:[stop]
<-------------------------------------->
[jenkins-2.387.1LTS] ... stop ...
[jenkins-2.387.1LTS] pid=56012
[jenkins-2.387.1LTS] stop success
更换插件更新地址为清华源
sed -i 's/https:\/\/updates.jenkins.io\/download/http:\/\/mirrors.tuna.tsinghua.edu.cn\/jenkins/g' /home/jenkins/jenkins_data/updates/default.json
sed -i 's/https:\/\/www.google.com/https:\/\/www.baidu.com/g' /home/jenkins/jenkins_data/updates/default.json
vi /home/jenkins/jenkins_data/hudson.model.UpdateCenter.xml
<?xml version='1.1' encoding='UTF-8'?>
<sites>
<site>
<id>default</id>
<url>https://mirrors.tuna.tsinghua.edu.cn/jenkins/updates/update-center.json</url>
</site>
</sites>
vi /etc/logrotate.d/jenkins
/home/jenkins/jenkins_logs/jenkins-2.387.1LTS.log {
su jenkins jenkins
copytruncate
daily
rotate 1000
missingok
compress
delaycompress
notifempty
create 644 jenkins jenkins
dateext
dateformat -%Y%m%d%H.%s
}
sh jenkins.sh start
本次操作服务名:[jenkins-2.387.1LTS]
本次操作选择:[start]
<-------------------------------------->
[jenkins-2.387.1LTS] ... start ...
当前路径:/home/jenkins
启动命令: nohup java -jar jenkins-2.387.1LTS.war --httpPort=8080 --prefix=/jenkins >> /home/jenkins/jenkins_logs/jenkins-2.387.1LTS.log 2>&1 &
[jenkins-2.387.1LTS] start success
看日志看初始密码
vi /home/jenkins/jenkins_logs/jenkins-2.387.1LTS.log
*************************************************************
*************************************************************
*************************************************************
Jenkins initial setup is required. An admin user has been created and a password ge
nerated.
Please use the following password to proceed to installation:
4215bf0dc5b5459382e5bd0fdbc0e403
This may also be found at: /home/jenkins/jenkins_data/secrets/initialAdminPassword
*************************************************************
*************************************************************
*************************************************************
再看一下进程确认一下
ps -ef |grep jenkins
jenkins 60319 1 13 17:30 pts/0 00:00:28 java -jar jenkins-2.387.1LTS.war --httpPort=8080 --prefix=/jenkins
jenkins 61253 60277 0 17:33 pts/0 00:00:00 grep --color=auto jenkins
浏览器访问http://192.168.3.111:8080/jenkins/
把刚才的密码复制进去,继续
选择插件来安装
根据自己的需要把不用的删掉,添加自己需要的
我这里取消了ant,Gradle,GitHub一系列
添加了GitLab,点击安装
安装完成,创建新用户
配置访问URL
这里有个红色的提示
在内置节点上构建可能是一个安全问题。您应该设置分布式生成。请参阅文档
直接点击dismiss即可
还有黄色的警告
第一个是插件的警告,初始化的时候有的插件可能会未安装成功
点击这里
点击重启更新,等待重启之后即可看到只有一个更新的提示,不用管他。
至此安装jenkins完毕。
进入系统管理后,系统管理–>插件管理,记得更新插件
之后,查看主目录是否正确,这里的主目录是机器上jenkins家目录环境变量
根据需要把编译源码整个过程需要的环境配置好
先在服务器上安装需要的软件
编译的代码依赖的是java8的jdk,所以不能用jenkins安装的17版本的,需要单独放置一套jdk,然后在jenkins内配置该jdk的路径
su - jenkins
上传包jdk-8u351-linux-x64.tar.gz
tar -zxf jdk-8u351-linux-x64.tar.gz
rm -f jdk-8u351-linux-x64.tar.gz
ll jdk1.8*
drwxrwxr-x 8 jenkins jenkins 4096 Mar 14 16:55 jdk1.8.0_351
部署之前要先安装jdk
su - jenkins
上传包
tar xvf apache-maven-3.8.7-bin.tar.gz
vi ~/.bash_profile
export MAVEN_HOME=/home/jenkins/apache-maven-3.8.7
export PATH=$MAVEN_HOME/bin:$PATH
source ~/.bash_profile
mvn -v
Apache Maven 3.8.7
mkdir /home/jenkins/apache-maven-3.8.7/repository
cd apache-maven-3.8.7/conf
vi settings.xml
maven默认存放地址看settings的52行:| Default: ${user.home}/.m2/repository
默认存放在用户家目录的隐藏文件.m2文件夹中
在55行插入下面内容
<localRepository>/home/jenkins/apache-maven-3.8.7/repository</localRepository>
vi settings.xml
找到159-165行<mirrors>mirrors>标签内替换内容
<mirror>
<id>nexus-aliyunid>
<mirrorOf>*mirrorOf>
<name>Nexus aliyunname>
<url>http://maven.aliyun.com/nexus/content/groups/publicurl>
mirror>
将下面的代码粘贴到settings中,放在<profiles>profiles>之间
<profile>
<id>jdk-1.8id>
<activation>
<activeByDefault>trueactiveByDefault>
<jdk>1.8jdk>
activation>
<properties>
<maven.compiler.source>1.8maven.compiler.source>
<maven.compiler.target>1.8maven.compiler.target>
<maven.compiler.compilerVersion>1.8maven.compiler.compilerVersion>
properties>
profile>
mvn help:system
[INFO] Scanning for projects...
...................略
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 17.885 s
[INFO] Finished at: 2023-04-14T15:57:49+08:00
[INFO] ------------------------------------------------------------------------
(目的是gitlab是https的方式,安装git需要先编译一下curl命令,不需要可以不做)
下载
https://curl.se/download.html
yum install gcc
su - jenkins
tar -zxf curl-7.88.1.tar.gz
rm -f curl-7.88.1.tar.gz
mv curl-7.88.1 curl-7.88.1h
mkdir curl-7.88.1
cd curl-7.88.1h
./configure --prefix=/home/jenkins/curl-7.88.1 --with-ssl --enable-tls-srp
make
make install
vi ~/.bash_profile
export CURL_ROOT=/opt/curl-7.76.1-ubuntu-x64
# 运行依赖
export LD_LIBRARY_PATH=$CURL_ROOT/lib:$LD_LIBRARY_PATH
# 开发依赖
export PATH=$CURL_ROOT/bin:$PATH
export CPATH=$CURL_ROOT/include:$CPATH
export LIBRARY_PATH=$CURL_ROOT/lib:$LIBRARY_PATH
source ~/.bash_profile
rm -rf ~/curl-7.88.1h/
(如果gitlab是https的方式,需要先编译一下curl命令,然后编译git时加上–with-curl参数)
下载
https://git-scm.com/download/linux
点击The latest version is 2.40.0.最后的版本号下载tar包
解压
tar -zxf git-2.40.0.tar.gz
rm -f git-2.40.0.tar.gz
mv git-2.40.0/ git-2.40.0h
mkdir git-2.40.0
安装编译环境
yum install curl-devel expat-devel gettext-devel openssl-devel zlib-devel gcc perl-ExtUtils-MakeMaker automake autoconf libtool make
安装上面编译环境的时候,yum自动帮你安装了git,这时候你需要先卸载这个旧版的git。
否则还是一个老版本
git --version
git version 1.8.3.1
yum remove git
(有依赖一起卸载掉没事不用管)
编译源码
cd git-2.40.0h
./configure --prefix=/home/jenkins/git-2.40.0 --with-curl --with-expat
make prefix=/home/jenkins/git-2.40.0 all
prefix里面填你想要放的文件夹位置
安装git
make prefix=/home/jenkins/git-2.40.0 install
配置环境变量
vim ~/.bash_profile
export GIT_HOME=/home/jenkins/git-2.40.0
export PATH=$GIT_HOME/bin:$PATH
source ~/.bash_profile
验证
git --version
git version 2.40.0
本地配置(本地可以不用配置,如果想本地使用git,可以如下配置)
git config --global user.name gituser
git config --global user.email [email protected]
git config --global push.default simple
git config --global --list
(这里我直接用yum安装的,编译安装等有时间搞一下)
yum install ansible -y
此时~/.bash_profile文件应该是:
PATH=$PATH:$HOME/.local/bin:$HOME/bin
export CURL_ROOT=/home/jenkins/curl-7.88.1
export LD_LIBRARY_PATH=$CURL_ROOT/lib:$LD_LIBRARY_PATH
export PATH=$CURL_ROOT/bin:$PATH
export CPATH=$CURL_ROOT/include:$CPATH
export LIBRARY_PATH=$CURL_ROOT/lib:$LIBRARY_PATH
export JAVA_HOME=/home/jenkins/jdk-17.0.6
export JENKINS_HOME=/home/jenkins/jenkins_data
export MAVEN_HOME=/home/jenkins/apache-maven-3.8.7
export GIT_HOME=/home/jenkins/git-2.40.0
export PATH=$HOME/bin:$JAVA_HOME/bin:$MAVEN_HOME/bin:$GIT_HOME/bin:$PATH
配置之前还需要安装几个插件
点进全局工具配置
Dashboard > 系统管理 > 全局工具配置
全局工具配置
Maven 配置
默认 settings 提供
文件系统中的 settings 文件
文件路径
/home/jenkins/apache-maven-3.8.7/conf/settings.xml
默认全局 settings 提供
文件系统中的全局 settings 文件
文件路径
/home/jenkins/apache-maven-3.8.7/conf/settings.xml
JDK
--新增JDK
JDK
别名
jdk1.8.0_351
JAVA_HOME
/home/jenkins/jdk1.8.0_351
自动安装(不选择)
Git installations
--Add Git
Git
Name
git-2.40.0
Path to Git executable
/home/jenkins/git-2.40.0/bin/git
自动安装(不选择)
Maven
--新增 Maven
Maven
Name
maven-3.8.7
MAVEN_HOME
/home/jenkins/apache-maven-3.8.7
自动安装(不选择)
Ansible
--新增 Ansible
Ansible
Name
ansible2.9.27
Path to ansible executables directory
/bin
自动安装(不选择)
一步一步操作
Dashboard
新建任务
输入一个任务名称
构建一个maven项目
确定
进入Configure页面
General--默认就好
源码管理
选择Git
Repositories
Repository URL
填写gitlab源码地址
Credentials
选择账号密码
没有的话点击添加,选择Usename With password,填写用户名密码备注,点击添加
Branches to build
指定分支(为空时代表any)
*/test
源码库浏览器
(自动)
构建触发器--默认就好
构建环境--默认就好
Pre Steps--默认就好,这是编译前的动作
Build
Root POM
pom.xml
Goals and options
clean package -DskipTests=true(这里我是跳过测试了)
高级--默认就好
Post Steps
选择Run only if build succeeds
其他的默认就好,我们稍后再配置
构建设置、构建后操作--默认就好
保存
点击进入项目
点击立即构建
点击左侧下面的编译过程中
查看控制台输出
第一次编译时可以看到:
拉取代码
Cloning the remote Git repository
Cloning repository **********
下载文件
First time build. Skipping changelog.
Parsing POMs
Downloaded artifact *********.pom
然后会有报错
Exception in thread "main" java.lang.UnsupportedClassVersionError: hudson/remoting/Launcher has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
然后显示
Finished: FAILURE
提示编译失败
这里的意思是jenkins的jdk版本只能大于等于11,而我们用来编译代码的jdk是8版本,所以失败
我们直接第二次构建,不用管报错
第二次编译:
拉取代码之后,会在后面显示
Exception in thread "main" java.lang.UnsupportedClassVersionError: hudson/remoting/Launcher has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
at *****************************
ERROR: ================================================================================
ERROR: Invalid project setup: Connection reset
ERROR: [JENKINS-18403][JENKINS-28294] JDK 'jdk1.8.0_351' not supported to run Maven projects.
ERROR: Maven projects have to be launched with a Java version greater or equal to the minimum version required by the controller.
ERROR: Use the Maven JDK Toolchains (plugin) to build your maven project with an older JDK.
ERROR: Retrying with agent Java and setting compile/test properties to point to /home/jenkins/jdk1.8.0_351.
ERROR: ================================================================================
Established TCP socket on 43238
[test] $ /home/jenkins/jdk-17.0.6/bin/java -cp*****************
我们可以看到jenkins自动换成了17版本的jdk进行运行,这里不用担心,编译出来的包还是可以使用的,之后每次编译都会出现这个报错的,我们不用管他
后面就是下载很多包,因为是第一次编译
[INFO] Downloading from nexus-aliyun:
编译之后会看到
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary for yggq 1.0-SNAPSHOT:
[INFO]
[INFO] zzx............................................... SUCCESS [ 3.224 s]
[INFO] zzx1 ........................................ SUCCESS [01:13 min]
[INFO] zzx2 ........................................... .SUCCESS [ 8.406 s]
[INFO] zzx3 ...........................................SUCCESS [ 18.337 s]
[INFO] zzx4 ....................................... .....SUCCESS [ 11.951 s]
[INFO] zzx5 ............................................ SUCCESS [ 3.081 s]
[INFO] zzx6 ............................................ SUCCESS [ 6.014 s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 02:11 min
[INFO] Finished at: 2023-04-14T18:56:31+08:00
[INFO] ------------------------------------------------------------------------
显示编译成功,然后后面jenkins会整理数据和文件
Waiting for Jenkins to finish collecting data
[JENKINS] Archiving /home/jenkins/jenkins_data/workspace/test/zzx1/target/zzx-1.0-SNAPSHOT.jar to com.xyx.zzx/zzx1/1.0-SNAPSHOT/zzx-1.0-SNAPSHOT.jar
能看到在工作空间下的target目录下生成了jar包,我们的编译是成功的,这个jar包就是我们要使用的jar包
channel stopped
Finished: SUCCESS
最后提示编译成功
这里我们只需要编写playbook即可,配置文件和主机列表到jenkins里配置即可
su - jenkins
mkdir playbook
cd playbook
vi jar.yml
我这个maven的项目下面有几个子项目
所以这个playbook需要通用性,可以在jenkins中指定ansible的变量,在playbook中多使用变量来实现通用性
jenkins完成编译后,利用编译后的动作将jar包放到指定目录下,playbook将jar包进行备份归档,再利用每个主机上的启动停止脚本来进行jar包的启动和停止
---
---
- name: "本机备份jar包"
hosts: localhost
tasks:
- name: "获取本机当前时间"
debug:
msg: "{{ hostvars['localhost']['ansible_date_time']['iso8601_basic_short'] }}"
register: localdate
- name: "查看版本包状态"
stat:
path: "{{ nasdir }}/{{ jarname }}"
register: jarstat
- debug:
var: jarstat.stat.exists
- name: "创建备份目录"
file:
path: "{{ nasdir }}/{{ localdate.msg }}"
state: directory
mode: 0777
- name: "转移jar包到备份文件夹"
copy:
src: "{{ nasdir }}/{{ jarname }}"
dest: "{{ nasdir }}/{{ localdate.msg }}"
- file:
path: "{{ nasdir }}/{{ jarname }}"
state: absent
- name: "更新版本信息"
lineinfile:
dest: "{{ nasdir }}/info.txt"
regexp: "^previous version:"
state: absent
create: yes
- replace:
path: "{{ nasdir }}/info.txt"
regexp: "lastest version"
replace: "previous version"
- lineinfile:
path: "{{ nasdir }}/info.txt"
regexp: 'add a line!'
line: "lastest version: {{ localdate.msg }}"
backrefs: no
- name: "jar自动上版"
hosts: host
gather_facts: false
serial: 1
tasks:
- name: "获取本机当前时间"
debug:
msg: "{{ hostvars['localhost']['ansible_date_time']['iso8601_basic_short'] }}"
register: localdate
- name: "查看版本包状态"
stat:
path: "{{ nasdir }}/{{ localdate.msg }}/{{ jarname }}"
register: jarstat
- debug:
var: jarstat.stat.exists
- name: "关闭进程"
shell: "sh ~/shutdown.sh"
register: shutdownsh
- debug:
var: shutdownsh.stdout_lines
- name: "删除旧版本包"
file:
path: "~/{{ jarname }}"
state: absent
- name: "拷贝版本包"
copy:
src: "{{ nasdir }}/{{ localdate.msg }}/{{ jarname }}"
dest: "~"
- name: "启动tomcat"
shell: "sh ~/start.sh"
register: startsh
- debug:
var: startsh.stdout_lines
根据playbook我们需要
远程到需要部署jar包的主机
su - root
useradd zzx
passwd zzx
mkdir /nas/testlog/
chown zzx:zzx /nas/testlog/
mkdir /nas/testpackage/
chown zzx:zzx /nas/testpackage/
vi mkdir /nas/testpackage/info.txt
lastest version:
previous version:
chown zzx:zzx /nas/testpackage/info.txt
su - root
vi /etc/logrotate.d/jar
/nas/testlog/outlog.log {
copytruncate
daily
rotate 7
missingok
compress
delaycompress
notifempty
create 644 zzx zzx
dateext
dateformat -%Y%m%d%H.%s
}
su - zzx
vi start.sh
#!/bin/bash
echo "开始启动"
/usr/sbin/logrotate -f /etc/logrotate.d/jar
nohup /usr/local/jdk1.8.0_351/bin/java -jar -Dfile.encoding=utf8 -Xms1024m -Xmx1024m /home/zzx/zzx-business-1.0-SNAPSHOT.jar --server.port=8848 --spring.profiles.active=test --logging.path=/nas/testlog/ >> /nas/testlog/outlog.log 2>&1 &
sleep 5
for ((i=1;i<=6;i++))
do
nacos=`grep -E 'NacosServiceRegistry - nacos registry, DEFAULT_GROUP \S* \S*:\S* register finished' /nas/testlog/outlog.log `
if [ -z "$nacos" ]
then
echo "请稍等。。。。"
sleep 5
else
echo "已启动!"
grep -E 'NacosServiceRegistry - nacos registry, DEFAULT_GROUP \S* \S*:\S* register finished' /nas/testlog/outlog.log
echo `ps -ef| grep 'zzx' | grep -v 'grep' |awk '{print $1,$2}'`
break
fi
done
vi shutdown.sh
#!/bin/bash
pid=`ps -ef| grep 'zzx' | grep -v 'grep' |awk '{print $2}'`
if [ ! -z "$pid" ]
then
kill $pid
fi
sleep 5
for ((i=1;i<10;i++))
do
pid2=`ps -ef| grep 'zzx' | grep -v 'grep' |awk '{print $2}'`
if [ ! -z "$pid2" ]
then
echo "请稍等。。。。"
sleep 5
else
echo "已关闭!"
break
fi
done
Dashboard > 系统管理 > Configure System
找到 Publish over SSH
点击新增
SSH Servers
SSH Server
Name
localhost
Hostname
127.0.0.1
Username
jenkins
Remote Directory
/
高级
勾选Use password authentication, or use a different key
Passphrase / Password
主机密码
下面的默认即可
点击Test Configuration进行测试
返回Success即成功
点击最下方应用
Dashboard > 你的项目 > Configuration
拉到最下面找到Post Steps
点选Run only if build succeeds
点击Add post-build step,选择Send files or execute commands over SSH
这步是为了编译后传输文件到指定位置
Send files or execute commands over SSH
SSH Publishers
SSH Server
Name
localhost(选择刚才添加的主机)
高级
点选Verbose output in console
其他默认
Transfers
Transfer Set
Source files
(这是编译出来的jar包位置,jenkins编译后默认在工作空间内,所以写相对路径)
zzx-test/target/zzx-1.0-SNAPSHOT.jar
Remove prefix
(我们只需要jar包,所以把前面的路径去掉,否则会创建相对路径)
zzx-test/target
Remote directory
(这个路径最前面的/会自动去掉,所以配置时需要看ssh主机的Remote Directory参数,配置成他的相对路径)
/nas/testpackage
Exec command
echo "传输版本包"
高级
默认即可
找到Post Steps
点选Run only if build succeeds
点击Add post-build step,选择Invoke Ansible Playbook
Ansible installation
ansible2.9.27
Playbook path
/home/jenkins/playbook/jar.yml
Inventory
选择Inline content
不勾选Dynamic inventory
Content
[host]
192.168.1.1
Host subset
不填,我实验填了就不好使了,原因请哪位大神告知一下
Credentials
主机用户名密码,没有的话添加一下凭证
Vault Credentials
默认即可
高级
Number of parallel processes
这里填1,并行数设置成1,进行滚动升级
Disable the host SSH key check
勾选上,不保存主机公钥,省的ssh升级之后登录报错
Unbuffered stdout
勾选上
Extra Variables
Key
jarname
Value
zzx-1.0-SNAPSHOT.jar
Key
nasdir
Value
/nas/testpackage
Key
logdir
Value
/nas/testlog/
最后点击保存
点击立即构建
打开控制台输出
在编译代码整理数据之后会看到
channel stopped
SSH: Connecting from host [zzx]
SSH: Connecting with configuration [localhost] ...
***
SSH: put [zzx-1.0-SNAPSHOT.jar]
SSH: OK
SSH: Opening exec channel ...
SSH: EXEC: channel open
SSH: EXEC: STDOUT/STDERR from command [echo "传输版本包"] ...
SSH: EXEC: connected
传输版本包
SSH: EXEC: completed after 201 ms
SSH: Disconnecting configuration [localhost] ...
SSH: Transferred 1 file(s)
可以看到ssh的配置生效了,jenkins把版本包放到了指定的目录下
接着看
[test] $ sshpass ******** /bin/ansible-playbook /home/jenkins/playbook/jar.yml -i /tmp/inventory4167368454137635701.ini -f 1 -u zzx -k -e jarname=zzx-1.0-SNAPSHOT.jar -e nasdir=/nas/testpackage -e logdir=/nas/testlog
PLAY [本机备份jar包] ****************************************************************
TASK [Gathering Facts] *********************************************************
ok: [localhost]
****
PLAY RECAP *********************************************************************
192.168.1.1 : ok=9 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
localhost : ok=10 changed=6 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Finished: SUCCESS
我们可以看到ansible的任务也执行成功
我们可以去主机上看各个文件,日志状态是否正确
至此,我们的jenkins+ansible就成功完成了