行僧

参与开源,努力提升。 我的GitHub地址:https://github.com/playingjoker

jenkins 自动化 pipeline脚本实现自动部署

    基于groovy脚本实现各个stage节点配置

    ## 第一步生成初始化参数
    ## 第二步收集用户部署节点及服务
    收集用户需要部署的各个服务以及部署节点信息,准备初始化shell和对应的docker镜像
    ## 第三步生成部署脚本
    生成shell脚本,并生成对应版本号,目标机器等信息,用于准备docker容器 最后上传shell脚本,用于远端调用
    ## 第四步远端调用部署脚本
    调用远端脚本并完成部署,最终打印远端部署日志输出到pipeline控制台

    
    #!/usr/bin/env groovy
    package pipeline
    
    def getInputParam(envNodeMap) {
        def envList = []
        envNodeMap.each{key, value->
            envList << key
        }
        def nodeMap = genServiceNode('', '')
        def projectList = []
        nodeMap.each{key, value->
            projectList << key
        }
        println(projectList)
        return [
                choice(choices: projectList.join('\n'), description: '选择要部署的项目', name: 'project'),
                choice(choices: envList.join('\n'), description: '选择要部署的环境', name: 'env'),
                string(defaultValue: '3.1.0', description: '请输入版本号', name: 'version'),
                choice(choices: ['SNAPSHOT','RELEASES'].join('\n'), description: '选择要部署的版本类型', name: 'type'),
    
        ]
    }
    //http://nexus.td.internal/nexus/repository/maven-releases/com/redhorse/df-alphaj-service/1.0.0/df-alphaj-service-1.0.0-assembly.zip
    def paramMap = [:]
    def envValueLabel = [
            '开发环境': "dev",
            '测试环境': "newtest",
            '准生产环境': "pre"
    ]
    def NEXUS_URL_PREFIX = "http://nexus.td.internal/nexus/repository"
    def JENKINS_CREDENTIALS_ID = "global_key"
    def PROJECT_TO_BE_DEPLOY = "ssh://git@192.168.15.160:20022/ttzt/df-deploy.git"
    def DOCKER_REGISTRY = "docker.registry.td.internal"
    stage("准备参数") {
        node {
            timestamps {
                def groupId = 'com.redhorse'
      def groupPath = groupId.replace('.', '/')
                def ext = 'zip'
      def classifier = 'assembly'
      def envNodeMap = initEvnNodeMap()
    
                timeout(30) { // 超时30分钟
      paramMap = input id: 'DfDeploy', message: '请选择要部署的服务, 请注意避开定时任务时间点!!!!!', ok: '提交', parameters: getInputParam(envNodeMap)
                }
                echo "${paramMap}"
      def workspace = pwd()
                def newVersion = paramMap.version
                def nexusRepo = 'maven-releases'
      //http://nexus.td.internal/nexus/repository/maven-snapshots/com/redhorse/df-alphaj-service/1.2.1-SNAPSHOT/maven-metadata.xml
      echo "${paramMap.type}"
      paramMap.versionSuffix = ""
      if ("${paramMap.type}".equalsIgnoreCase('SNAPSHOT')) {
                    nexusRepo = 'maven-snapshots'
      paramMap.versionSuffix = "-SNAPSHOT"
      def versionXmlUrl = "${NEXUS_URL_PREFIX}/${nexusRepo}/${groupPath}/${paramMap.project}/${paramMap.version}${paramMap.versionSuffix}/maven-metadata.xml"
    
      def xmlPath = "${workspace}/${paramMap.project}-artifactVersion.xml"
    
      def curlXmlUrl = "curl -H \'Cache-Control: no-cache\' -t utf-8 -s -L -o ${xmlPath} ${versionXmlUrl}"
      print curlXmlUrl
                    sh curlXmlUrl
                    def scriptStr = "grep -m 1 \\\\> ${workspace}/${paramMap.project}-artifactVersion.xml | sed -e " +
                            "'s/\\(.*\\)<\\/value>/\\1/' | sed -e 's/ //g'"
    
      newVersion = sh returnStdout: true, script: scriptStr
                    newVersion = "${newVersion}".trim()
                    echo newVersion
                    paramMap.versionXmlUrl = versionXmlUrl
                }
                def downloadUrl = "${NEXUS_URL_PREFIX}/${nexusRepo}/${groupPath}/${paramMap.project}/${paramMap.version}${paramMap.versionSuffix}/${paramMap.project}-${newVersion}-${classifier}.${ext}"
    
      paramMap.downloadUrl = downloadUrl
                paramMap.envNodeMap = envNodeMap
    
                //下载git权限文件
      git branch: "develop", credentialsId: "${JENKINS_CREDENTIALS_ID}", url: "${PROJECT_TO_BE_DEPLOY}"
      sh "ls -la"
      sh "rm -rf ./id_rsa ./docker_start_project.sh "
      sh "ls -la"
      if (fileExists("${workspace}/src/resources/id_rsa")) {
                    dir("${workspace}/src/resources/") {
                        stash name: "id_rsa", includes: "id_rsa"
      }
                }
                else {
                    echo "秘钥文件不存在"
      }
                if (fileExists("${workspace}/src/resources/docker_start_project.sh")) {
                    dir("${workspace}/src/resources/") {
                        stash name: "docker_start_project.sh", includes: "docker_start_project.sh"
      }
                }
                else {
                    echo "秘钥文件不存在"
      }
                unstash "id_rsa"
      sh "chmod 0600 id_rsa"
      }
    
        }
    }
    
    stage("上传部署脚本") {
        node {
            timestamps {
    
                def envNodeMap = paramMap.envNodeMap
                def workspace = pwd()
    
                def targetIp = "${envNodeMap[paramMap.env.toString()][paramMap.project.toString()]}"
    
      def sshParam = "-i ${workspace}/id_rsa -o StrictHostKeyChecking=no"
      def ssh = "ssh ${sshParam} dx@${targetIp} "
      def scp = "scp ${sshParam} "
      paramMap.ssh = ssh
    
                unstash "docker_start_project.sh"
      echo "修改文件权限"
      sh "chmod 0755 docker_start_project.sh"
      sh "cat docker_start_project.sh"
    
      def targetPwdsh = sh "${ssh} pwd"
      echo "删除远端部署脚本"
      echo "${ssh} rm -rf ./docker_start_project.sh"  sh "${ssh} rm -rf ./docker_start_project.sh"
      echo "复制部署脚本到远端"
      echo "${scp} docker_start_project.sh dx@${targetIp}:~"
      sh "${scp} docker_start_project.sh dx@${targetIp}:~"
    
      echo "${ssh} chmod +x ./docker_start_project.sh"  sh "${ssh} chmod +x ./docker_start_project.sh"  }
    
        }
    
    }
    
    stage('重启服务') {
        node {
            unstash "id_rsa"
      sh "chmod 0600 id_rsa"
      def ssh = paramMap.ssh
            def projectName = paramMap.project.toString()
            echo "重启 <${paramMap.env.toString()}> 环境,参数: ${envValueLabel[paramMap.env.toString()]}"
      def profileActive = "${envValueLabel[paramMap.env.toString()]}"
    
      sh "${ssh} ./docker_start_project.sh ${projectName} ${paramMap.version}${paramMap.versionSuffix} -Dspring.profiles.active=${profileActive}"
    
      echo "重启服务成功!"
      }
    }
    
    stage('读取启动日志') {
        node {
            def ssh = paramMap.ssh
            def projectName = paramMap.project.toString()
            echo "休眠15秒等待日志"
      sleep(15)
            sh "${ssh} ./docker_start_project.sh ${projectName} ${paramMap.version}${paramMap.versionSuffix} logs"  echo " success! "
      }
    }
    
    static Map genServiceNode(serviceNode, clientNode) {
        return [
                'df-trade-service': serviceNode.toString(),
                'df-cms-service': serviceNode.toString(),
                'df-public-service': serviceNode.toString(),
                'df-user-service': serviceNode.toString(),
                'df-aps': clientNode.toString(),
                'df-autotask': clientNode.toString(),
                'df-web': clientNode.toString(),
                'df-manager': clientNode.toString(),
        ]
    }
    
    static Map initEvnNodeMap() {
        def devServiceNode = '192.168.15.134'
      def devClientNode = '192.168.15.136'
      def testServiceNode = '192.168.15.202'
      def testClientNode = '192.168.15.201'
      def preServiceNode = '192.168.15.204'
      def preClientNode = '192.168.15.203'
    
      return [
                //'开发环境': genServiceNode(devServiceNode, devClientNode),
      '测试环境': genServiceNode(testServiceNode, testClientNode),
                '准生产环境': genServiceNode(preServiceNode, preClientNode),
        ]
    }
    
    
    评论
    validate