Skip to content

Jenkins Pipeline 使用 Maven 打包并发布到 Linux 服务器

🏷️ Jenkins

在 Jenkins 中使用 Maven 打包项目后发布到 Linux 服务器。

1. 安装 SSH Pipeline Steps 插件

Manage Jenkins => Manage Plugins 的 可选插件 标签中查询 SSH Pipeline Steps,勾选后安装。

2. pipeline 脚本

可以写在 Jenkinsfile 中,用法参考 这篇博客

groovy
pipeline {
    agent any

    tools {
        jdk 'jdk-8u111'
        maven 'mvn-3.6.1'
    }

    stages {
        stage('Build') {
            steps {
                bat "mvn clean package"
            }
        }
        stage ('Publish to Test-D') {
            steps {
                script {
                    def remote = [:]
                    remote.name = 'OctopusESApi'
                    remote.host ='192.168.0.1'
                    remote.user = 'root'
                    remote.password ='password'
                    remote.allowAnyHosts= true
                    writeFile file:'stop.sh', text: '#!/bin/bash \n  \n stop_api(){ \n es_api=$(ss -lnp|grep 8888|awk -F \',\' \'{print $2}\') \n  \n if [ ! -z $es_api ]; then \n     kill -9 $es_api \n     if [ $? -eq 0 ]; then \n         echo "ES-API-D shutdown successfully !" \n     else \n         echo "ES-API-D failed to shutdown !" \n         exit 1 \n     fi \n else \n     echo "ES-API-D is not active !" \n     exit 1 \n fi \n } \n  \n stop_api \n '
                    writeFile file:'start.sh', text: '#!/bin/sh \n cd /opt/elastic-api-d/ \n java -jar -Xms8192m -Xmx8192m OctopusESApi.jar >/dev/null &'
                    sshScript remote: remote,script: "stop.sh"
                    sleep 5
                    sshPut remote: remote, from: 'OctopusESApi/target/OctopusESApi.jar', into: '/opt/elastic-api-d/'
                    sshScript remote: remote,script: "start.sh"
                }
            }
        }
    }
}

参考

  1. Jenkins 流水线 pipeline 中 SSH 方式登录远程机器
  2. jenkinsci/ssh-steps-plugin