T O P

[资源分享]     Jenkins使用pipeline部署服务到远程服务器

  • By - 楼主

  • 2022-08-09 16:02:13
  • 写这篇文章是对之前搭建Jenkins做的修改和完善,让jenkins更好的为我们服务

    Docker搭建Jenkins服务

    使用过程中遇到的问题:
      为方便部署,打算将jenkins用到的jdk11、maven、gradle工具下载下来(方便以后部署使用),然后挂载到jenkins容器内部
      在使用maven打包服务过程中,发现每次构建都要重新下载maven依赖,耗时间耗内存,将jenkins容器内的maven仓库做持久化存储
      docker部署jenkins一般是使用jenkins/jenkins:lts-jdk11稳定版镜像,如出现插件下载失败,版本太老,可将容器内jenkins.war替换成最新版
      容器时间和宿主机时间同步
      docker启动容器限制内存策略。如果不限制会把内存都吃掉。
      jenkins构建项目的数据持久化存储

    最终的docker搭建jenkins脚本就变成:
    docker run --name jenkins -p 8081:8080 -p 50000:50000 \
    -u root --privileged=true -m 1G --memory-swap=3G \
    -v /home/docker/server/jenkins/data:/var/jenkins_home \
    -v /var/run/docker.sock:/var/run/docker.sock \
    -v /usr/bin/docker:/usr/bin/docker \
    -v /home/docker/server/jenkins/m2:/root/.m2 \
    -v /home/docker/server/jenkins/gradle:/root/.gradle \
    -v /home/docker/server/jenkins/pack/apache-maven-3.5.4:/usr/local/maven \
    -v /home/docker/server/jenkins/pack/gradle6.4:/usr/local/gradle \
    -v /home/docker/server/jenkins/pack/jdk1.8.0_171:/usr/local/jdk \
    -v /home/docker/server/jenkins/pack/jdk-11.0.9:/usr/local/jdk11 \
    -v /etc/localtime:/etc/localtime \
    -d jenkins/jenkins:lts-jdk11
    

      然后访问jenkins,安装插件:

        Locale        汉化插件(如汉化不完全,下载此插件)
        Maven Integration  构建maven项目插件
        Publish over SSH    使用ssh免密登录到目标服务器
        Deploy to container 用于部署war程序到tomcat中
        git parameter    选择指定分支进行构建的功能
        pipeline       流水线脚本
        Pipeline Stage View Plugin  构建过程图示

      配置jdk、maven、gradle环境变量

      配置应用服务器地址及账号:

        系统管理——>系统配置——> Publish over SSH

        

    Pipeline脚本部署服务到远程服务器

    新建流水线任务
    进入任务配置—参数配置—git参数,选择代码分支
    流水线语法—选择sshPublisher: Send build artifacts over SSH

      点击生成流水线脚本,复制到任务的流水线脚本中

       

      流水线脚本以及生成流水线语法的入口,有其他需求也可以用它生成

        

    完整的流水线脚本如下:

    #!/usr/bin/env groovy
    
    def desc_ip = "10.249.29.22"
    def desc_path = "/server/temp"
    def app_name = "ll-heat"
    def app_file = "${app_name}-0.0.1-SNAPSHOT.jar"
    def install_path = "/server/${app_name}"
    def target_path = "target/"
    def target_file = "target/${app_file}"
    def log_file = "${app_name}.log"
    def git_address = "https://git.ecashback.com.cn/zhenhongxue/ll-heat.git"
    def git_auth = "fe896e04-3743-4931-83f8-32d716461388"
    def JAVA_OPTS = "-Xms128m -Xmx256m -Xmn64m -Dfile.encoding=UTF8 -Dspring.profiles.active=test"
    	
    pipeline {
      agent any
    
      stages {
        stage('拉取代码') {
          steps {
            checkout([$class: 'GitSCM', branches: [[name: '${branch}']], userRemoteConfigs: [[credentialsId: "${git_auth}", url: "${git_address}"]]])
          }
        }
        
        stage('代码编译') {
          steps {
            sh  """
                pwd
                JAVA_HOME=/usr/local/jdk
                PATH=$JAVA_HOME/bin:/usr/local/maven/bin:$PATH
                mvn clean package -Dmaven.test.skip=true
                """
          }
        }
    	
        stage('远程启动服务') {
          steps {
            sshPublisher(publishers: [sshPublisherDesc(configName: "${desc_ip}", transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: 
            """
            cd ${install_path}
            pwd
            ps -ef | grep ll-heat-0.0.1-SNAPSHOT.jar | grep -v grep |awk '{print \$2}' |xargs kill -9
            mv ${desc_path}/${app_file} ./
            java -jar ${JAVA_OPTS} ${app_file} >${log_file} &
            """, execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: "${desc_path}", remoteDirectorySDF: false, removePrefix: "${target_path}", sourceFiles: "${target_file}")], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: true)])
          }
        }
      }
    } 

    pipeline脚本需要注意:变量的使用需要加${},如果是在pipeline语法中生成的语句,变量的使用需要加双引号"${}"

      脚本写完后会提示哪里有错误需要怎么改,要注意特殊字符需要转义处理,如'{print \$2}'需要转义

     

    构建过程中遇到的错误:

    1、SSH出错:IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
    Someone could be eavesdropping on you right now (man-in-the-middle attack)!
    It is also possible that a host key has just been changed.
    The fingerprint for the ECDSA key sent by the remote host is
    SHA256:uLW/iHik7jxKZ6IRgRV7pfWAKuBgZGxInXba1aSb8hA.
    Please contact your system administrator.
    Add correct host key in /home/docker/.ssh/known_hosts to get rid of this message.
    Offending ECDSA key in /home/docker/.ssh/known_hosts:3
    ECDSA host key for 192.168.1.22 has changed and you have requested strict checking.
    Host key verification failed.

    原因:控制端保存的被控制端秘钥改变,导致SSH错误
    解决方案:需要删除控制端保存的秘钥,然后重新SSH登录
        cat ~/.ssh/know_hosts
        删除文件中对应的主机和秘钥记录

        ssh 192.168.1.22
        输入密码就可以了

    2、publish over ssh传输文件数为0
      SSH: Connecting from host [test-22]
      SSH: Connecting with configuration [test-22] ...
      SSH: Disconnecting configuration [test-22] ...
      SSH: Transferred 0 file(s)
      Build step 'Send files or execute commands over SSH' changed build result to SUCCESS
      Finished: SUCCESS
    原因:源文件的位置没写对
         
     解决:可以在构建日志里看到jenkins运行的位置和jar包位置
         
        

       因为jenkins运行位置是/var/jenkins_home/workspaces/ll-heat,所以源文件jar包的位置应该写target/ll-heat-0.0.1-SNAPSHOP.jar

     

    本帖子中包含资源

    您需要 登录 才可以下载,没有帐号?立即注册