本文基于文档https://blog.csdn.net/qq_25337221/article/details/106160024和
https://blog.csdn.net/qq_25337221/article/details/106185232编写。
主要是将一个war包项目发布到目标服务器,并远程执行Tomcat。本实例使用之所以未使用springboot,主要是增强一些难度系数,进一步加强jenkins的学习。后续将进一步优化与改进。本实例仍然是入门项目。
这里一共分三步:
#ssh-keygen -t rsa -P ""
# scp /root/.ssh/id_rsa.pub root@target ip:/root
# cat /root/id_rsa.pub >> .ssh/authorized_keys
#!/bin/bash
pid=$(ps -ef | grep 8080 | grep -v grep | awk '{print $2}')
if [ -n "$pid" ]; then
echo $pid
/usr/local/apache-tomcat/bin/shutdown.sh
fi
rm -rf /usr/local/apache-tomcat/demo*
cp -rf /root/demo/demo.war /usr/local/apache-tomcat/webapps
/usr/local/apache-tomcat/bin/startup.sh
在流水线编写如下脚本:
def getHost(){
def remote = [:]
remote.name = 'targetServer'
remote.host = 'targetIPAddress'
remote.user = 'root'
remote.port = 22
remote.password = 'targetPassword'
remote.allowAnyHosts = true
return remote
}
pipeline{
agent any
tools {
gradle 'gradle6.0.1'
jdk 'jdk1.8'
}
environment{
TASK_NAME="remote-demo-pipline"
PROJECT="demo.war"
PROJECT_NAME="demo"
}
options{
buildDiscarder(logRotator(numToKeepStr: '10'))
timestamps()
}
triggers{
pollSCM('H/1 * * * *')
}
stages{
stage('init-server'){
steps {
script {
server = getHost()
}
}
}
stage('Preparation'){
steps{
echo 'pulling code'
/*git code*/
}
}
stage('Build'){
steps{
script{
echo 'Stopping Application'
echo 'starting build'
sh './gradlew clean build -x test'
}
}
}
stage('Deploy'){
steps{
script{
echo 'copy new project'
sh 'scp /var/lib/jenkins/workspace/$TASK_NAME/build/libs/$PROJECT root@targetIP:/root/demo'
echo "starting project"
sshCommand remote: server, command: "/root/demo/start.sh"
echo "startup success!"
}
}
}
}
post {
success {
emailext (
subject: "SUCCESSFUL: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
body: """ SUCCESSFUL: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':
Check console output at "${env.JOB_NAME} [${env.BUILD_NUMBER}]"
to: "[email protected],[email protected]",
from: "[email protected]"
)
slackSend channel: "#success-demo", message: "Content Build and Validate Succeded for ${env.CONTENT_GIT_REPO} for Repository ${env.CONTENT_GIT_URL} by ${env.JOB_NAME} (<${env.BUILD_URL}|Open>)", color: 'success', tokenCredentialId: 'slack-token'
}
failure {
emailext (
subject: "FAILED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
body: """ FAILED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':
Check console output at "${env.JOB_NAME} [${env.BUILD_NUMBER}]"
to: "[email protected],[email protected]",
from: "[email protected]"
)
slackSend channel: "# failure-jenkins", message: "Content Build and Validate FAILED for ${env.CONTENT_GIT_REPO} for Repository ${env.CONTENT_GIT_URL} by ${env.JOB_NAME} (<${env.BUILD_URL}|Open>)", color: 'warning', tokenCredentialId: 'slack-token'
}
}
}
2. jenkins 部署项目到远程服务器: https://blog.csdn.net/catoop/article/details/100511027
本内容由安康学院“雨季”原创。