jenkins部署java程序

2023-07-01 14:55:08 浏览数 (3)

# 编译发布jenkinsfile脚本如下

代码语言:javascript复制
pipeline {
    agent { label "jenkins-slave4" }
    parameters {
        string(name: 'version_number', defaultValue: '', description: '')
        gitParameter (branch:'', branchFilter: 'origin/(.*)', defaultValue: 'develop', description: '选择将要构建的分支', name: 'TAG', quickFilterEnabled: true, selectedValue: 'TOP', sortMode: 'DESCENDING_SMART', tagFilter: '*', type: 'PT_BRANCH_TAG', useRepository: 'ssh://git@xxxx.git')
    }
    options {
        // 表示保留50次构建历史
        buildDiscarder(logRotator(numToKeepStr: '50'))
    }
    tools { maven 'apache-maven-3.5.4' }
    stages {
        stage('CleanWorkspace') {
            steps {
                cleanWs()
            }
        }
        stage('拉取代码') {
                    steps {
                        dir("${WORKSPACE}/"){
                            script {
                                try {
checkout([$class: 'GitSCM', branches: [[name: '$TAG']], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'CloneOption', depth: 1, noTags: false, reference: '', shallow: true]], submoduleCfg: [], userRemoteConfigs: [[url: "ssh://git@xxxx.git"]]])
                            env.COMMIT_ID = sh(script: 'git log --pretty=format:%h',  returnStdout: true).trim() // 提交ID
                            env.COMMIT_USER = sh(script: 'git log --pretty=format:%an', returnStdout: true).trim() // 提交者
                            env.COMMIT_TIME = sh(script: 'git log --pretty=format:%ai', returnStdout: true).trim() // 提交时间
                            env.COMMIT_INFO = sh(script: 'git log --pretty=format:%s',  returnStdout: true).trim() // 提交信息                                   
                                }catch(exc) {
                                    env.REASON = "拉取代码出错"
                                    throw(exc)
                                }
                            }
                        }
                    }
                }
        stage('编译') {

            steps{
            script{
                try{
                    env.GIT_TREE_STATE="clean"
                    env.BUILD_DATE=sh(script: "echo `date ' %Y%m%d%H%M%S'`", returnStdout: true)
                }catch(exc){
                    env.Reason="执行出错"
                    throw(exc)
                }
            }
            
            sh """
			# 正常找包
			# mvn clean package -Dmaven.test.skip=true
			# 指定配置文件打包(使用-U参数: 该参数确保集成基于最新的状态)
			mvn clean package -U -Dmaven.test.skip=true

             """
            }
        }
        stage('部署服务') {
            steps {
                ansiblePlaybook become: true, becomeUser: null, credentialsId: 'deploy_pro', extras: '--extra-vars "WORKSPACE=${WORKSPACE}"', inventory: '/var/jenkins_home/ansible/hosts', playbook: '/var/jenkins_home/ansible/gg/gg_openapi.yml', sudoUser: null, disableHostKeyChecking: true
            }
        }
         
    }
    post {
        always {
            wrap([$class: 'BuildUser']){
                script{
                    currentBuild.description = "提交者: ${COMMIT_USER}" // 添加说明信息
                    currentBuild.description  = "n提交ID: ${COMMIT_ID}" // 添加说明信息
                    currentBuild.description  = "n提交时间: ${COMMIT_TIME}" // 添加说明信息
                    currentBuild.description  = "n版本号: ${BUILD_NUMBER}" // 添加说明信息
                    sh "printenv"
                }
            }
        }
    }    
}

gg_openapi.yml

代码语言:javascript复制
- hosts: openapi
  remote_user: gg
  serial: 1
  max_fail_percentage: 0
  gather_facts: false
  tasks:
  - name: get version
    shell: ls /data/jenkins/workspace/gg-face-openapi/target/*.jar |awk -F '[-]' '{print $NF}'|awk -F '.jar' '{print $1}'
    register: version
    connection: local
  - name: upload jar
    copy: src=/data/jenkins/workspace/gg-face-openapi/target/gg-face-openapi-{{ item }}.jar dest=/data/applications/
    with_items: "{{ version.stdout }}"
  - name: run jar
    shell: /data/applications/run_face.sh gg-face-openapi {{ item }} && sleep 60
    with_items: "{{ version.stdout }}"

run_face.sh脚本

代码语言:javascript复制
#!/bin/bash
export JAVA_HOME=/usr/local/jdk1.8.0_201
PATH=$PATH:$JAVA_HOME/bin
NAME=$1
VERSION=$2
PORT=$3
logbk=`date " %Y%m%d_%H%M"`
echo $NAME
ID=`ps -ef | grep "$NAME" | grep -v "$0" | grep -v "grep" | awk '{print $2}'`
if [ ! $NAME ]; then
echo "执行失败,请添加微服务名."
else
for id in $ID
do
kill -9 $id
echo "killed $id"
done
fi
mv /data/applications/$NAME.log /data/applications/logs/$NAME.log-$logbk
nohup java -server -Xms768m -Xmx768m -Xmn256m -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=256m -Xverify:none -XX: DisableExplicitGC -Djava.awt.headless=true -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=$PORT,suspend=n -Duser.timezone=Asia/Shanghai -Denv=pro -javaagent:/usr/local/skywalking-agent/agent/skywalking-agent.jar -Dskywalking.agent.service_name=$1 -jar /data/applications/$NAME-$VERSION.jar  > /data/applications/$NAME.log 2>&1 &

0 人点赞