首页 > 其他分享 >4.6 pipeline 生产配置实例

4.6 pipeline 生产配置实例

时间:2024-07-09 13:44:01浏览次数:20  
标签:pipeline 4.6 实例 sh ansible steps env echo stage

pipeline配置java项目

pipeline {
    agent { label 'slave' }
    options {
        timestamps()
        disableConcurrentBuilds()
        buildDiscarder(
            logRotator(
                numToKeepStr: '20',
                daysToKeepStr: '30',
            )
        )
    }
    parameters {
        choice(
           name: "DEPLOY_FLAG",
           choices: ['deploy', 'rollback'],
           description: "发布/回滚"
        )
    }
    /*=======================================常修改变量-start=======================================*/
    environment {
        gitUrl = "git地址"
        branchName = "分支名称"
        gitlabCredentialsId = "认证凭证"
        projectRunDir = "项目运行目录"
        jobName = "${env.JOB_NAME}"
        serviceName = "服务名称"
        serviceType = "jar"
        runHosts = "192.168.167.xx,192.168.167.xx"
        rollbackVersion = ""
    }
    stages {
        stage('Deploy'){
            when {
                expression { return params.DEPLOY_FLAG == 'deploy' }
            }
            stages {
                stage('Pre Env') {
                    steps {
                        echo "======================================项目名称 = ${env.JOB_NAME}"
                        echo "======================================项目 URL = ${gitUrl}"
                        echo "======================================项目分支 = ${branchName}"
                        echo "======================================当前编译版本号 = ${env.BUILD_NUMBER}"
                    }
                }
                stage('Git Clone') {
                    steps {
                        git branch: "${branchName}",
                        credentialsId: "${gitlabCredentialsId}",
                        url: "${gitUrl}"
                    }
                }
                stage('Mvn Build') {
                    steps {
                        withMaven(jdk: 'jdk1.8', maven: 'maven') {
                            sh "mvn clean package -Dmaven.test.skip=true -U -f ${serviceName}/pom.xml"
                        }
                    }
                }
                stage('Ansible Deploy') {
                    steps{
                        script {
                            sleep 5
                            ansiColor('xterm') {
                                ansiblePlaybook colorized: true, extras: '-e "directory=${projectRunDir}" -e "job=${jobName}" -e "service=${serviceName}" -e "type=${serviceType}"', installation: 'ansible', inventory: '/etc/ansible/hosts.yml', limit: "${runHosts}", playbook: '/etc/ansible/playbook/deploy-jenkins.yml'                            
                            }
                        }
                    }
                }
            }   
        }
        stage('Rollback') {
            when {
                expression { return params.DEPLOY_FLAG == 'rollback' }
            }
            steps{
                script {
                    rollbackVersion = input(
                        message: "请填写要回滚的版本",
                        parameters: [
                            string(name:'last_number')
                        ]
                    )
                    sh """
                        echo "正在回滚至就近第${rollbackVersion}个版本"
                        ansible ${runHosts} -m shell -a "sh ${projectRunDir}/rollback.sh ${rollbackVersion} ${serviceName}"
                    """
                }
            }
        }
    }
    post {
        always {
            deleteDir()
        }
        success {
            echo 'This task is successful!'
        }
    }
}
 

pipeline 配置前端项目

vue

pipeline {
    agent { label 'master'}

    options {
        timestamps()
        disableConcurrentBuilds()
        buildDiscarder(
            logRotator(
                numToKeepStr: '20',
                daysToKeepStr: '30',
            )
        )
    }

    parameters {
        choice(
           name: "DEPLOY_FLAG",
           choices: ['deploy', 'rollback'],
           description: "发布/回滚"
        )
    }

    /*=======================================常修改变量-start=======================================*/

    environment {
        gitUrl = "http://gitlab.schengle.com/driving-frontend/h5.git"
        branchName = "master"
        gitlabCredentialsId = "437c69b5-a874-4da6-8fe1-61e0275fdf0d"
        projectBuildDir = "build"
        projectBuildPath = "${env.WORKSPACE}/${projectBuildDir}/"
        nginxIp = "192.168.16.141"
        nginxHtmlRoot = "/tmp/${env.JOB_NAME}"
        owner = "font"
        group = "font"
        backupRootDir = "/opt/backup"
        backupJob = "${backupRootDir}/${env.JOB_NAME}"
        backupDir = "${backupJob}/${env.BUILD_NUMBER}"
        rollbackVersion = ""
    }

    /*=======================================常修改变量-end=======================================*/

    stages {
        stage('Deploy') {
            when {
                expression { return params.DEPLOY_FLAG == 'deploy' }
            }
            stages {
                stage('Pre Env') {
                    steps {
                        echo "======================================项目名称 = ${env.JOB_NAME}"
                        echo "======================================项目 URL = ${gitUrl}"
                        echo "======================================项目分支 = ${branchName}"
                        echo "======================================当前编译版本号 = ${env.BUILD_NUMBER}"
                        echo "======================================项目 Build 文件夹路径 = ${projectBuildPath}"
                        echo "======================================项目 Nginx 的 ROOT 路径 = ${nginxHtmlRoot}"
                    }
                }

                stage('Git Clone') {
                    steps {
                        git branch: "${branchName}",
                        credentialsId: "${gitlabCredentialsId}",
                        url: "${gitUrl}"
                    } 
                }

                stage('NPM Install') {
                    steps {
                        nodejs('nodejs') {
                            sh "npm install"
                        }
                    }
                }

                stage('NPM Build') {
                    steps {
                        nodejs('nodejs') {
                            sh "npm run build"
                        }
                    }
                }

                stage('Backup') {
                    agent { label 'ansible'}
                    steps {
                        script {
                            try {
                                isItBackupToday = sh (returnStatus: true, script:'ansible ${nginxIp} -m shell -a "ls -l --time-style=+%D ${backupJob} | grep $(date +%D)"')
                                if (isItBackupToday !=0){
                                    try {
                                        sh 'ansible ${nginxIp} -m file -a "path=${backupDir} state=directory owner=${owner} group=${group}"'
                                        sh 'ansible ${nginxIp} -m shell -a "cp -a ${nginxHtmlRoot}/* ${backupDir}"'
                                    }
                                    catch (exc) {
                                        echo 'Something failed!'
                                    }  
                                }
                            }
                            catch (exc) {
                                echo 'Something failed!'
                            }                             
                        }
                    }
                }

                stage('Nginx Deploy') {
                    agent { label 'ansible'}
                    steps {
                        sh 'ansible ${nginxIp} -m synchronize -a "src=${projectBuildPath} dest=${nginxHtmlRoot} delete=yes"'
                        sh 'ansible ${nginxIp} -m file -a "path=${nginxHtmlRoot} owner=${owner} group=${group} recurse=yes"'
                    }
                }

                stage('Tar Build') {
                    steps {
                        sh "tar -zcf  ${env.JOB_NAME}.tar.gz ${projectBuildDir}"
                    }
                }

                stage('Archive Artifacts') {
                    steps {
                        archiveArtifacts "${env.JOB_NAME}.tar.gz"
                    }
                }
            }
        }

        stage('Rollback') {
            when {
                expression { return params.DEPLOY_FLAG == 'rollback' }
            }
            agent { label 'ansible'}
            steps{
                script {
                    sh 'ansible ${nginxIp} -m shell -a "ls -l  ${backupJob}" | grep -v "CHANGED"'
                    rollbackVersion = input(
                        message: "请填写要回滚的版本",
                        parameters: [
                            string(name:'BUILD_NUMBER')
                        ]
                    )
                    sh 'ansible ${nginxIp} -m file -a "path=${nginxHtmlRoot} state=absent"'
                    sh 'ansible ${nginxIp} -m file -a "path=${nginxHtmlRoot} state=directory owner=${owner} group=${group}"'                    
                    withEnv(["rollbackVersion=${rollbackVersion}"]){
                        sh 'ansible ${nginxIp} -m shell -a "cp -a  ${backupJob}/${rollbackVersion}/* ${nginxHtmlRoot}"'
                    }
                }
            }
        }
    }
}
 

这个jenkinsfile中有保存 制品,

需要注意的是:制品的保存时间,和jenkins丢弃旧的构建参数,相同

局部变量的定义和传递

自定义变量(局部)

def username = 'Jenkins'
echo "Hello Mr.${username}"
 

环境变量(局部)

withEnv(['MYTOOL_HOME=/usr/local/mytool']){
    sh '$MYTOOL_HOME/bin/start'
}
 

exit code, stdout and stderr 返回值和输出

其做法是,把stdout定向到一个文件,sh 配置 returnStatus: true,它的返回是一个0或非0的整数,然后从文件读取stdout的内容。stderr同理可得。

def status = sh(returnStatus: true, script: "git merge --no-edit $branches > merge_output.txt")
if (status != 0) {
  currentBuild.result = 'FAILED'
  def output = readFile('merge_output.txt').trim()
  slackSend channel: SLACK_CHANNEL, message: "<${env.JOB_URL}|${env.JOB_NAME}> ran into an error merging the PR branches into the ${TARGET_BRANCH} branch:\n```\n${output}\n```\n<${env.BUILD_URL}/console|See the full output>", color: 'warning', tokenCredentialId: 'slack-token'
  error 'Merge conflict'
}
sh 'rm merge_output.txt'
 

标签:pipeline,4.6,实例,sh,ansible,steps,env,echo,stage
From: https://www.cnblogs.com/david-cloud/p/18291624

相关文章

  • Qt 控件的简单实例化
    记录一个初学小白的学习过程,记录一些浅显的学习笔记GroupBoxGroupBox控件的作用是组织界面元素,将一组相关的控件组合在一起,并在顶部显示一个标题。基类:QWidget (第一部分是widget.h)(第二部分是widget.cpp)#ifndefWIDGET_H#defineWIDGET_H#include<QWidget>#inc......
  • 【视频讲解】Python、R时间卷积神经网络TCN与CNN、RNN预测时间序列3实例附代码数据
    全文链接:https://tecdat.cn/?p=36944原文出处:拓端数据部落公众号本文旨在探讨时间卷积网络(TemporalConvolutionalNetwork,TCN)与CNN、RNN在预测任务中的应用。通过引入TCN模型,我们尝试解决时间序列数据中的复杂依赖关系,以提高预测的准确性。本文首先介绍了TCN的基本原理,随后详......
  • MathType7.4.6.9破解永久免费版本安装包下载
    亲爱的朋友们,今天我要给你们种草一款超实用的工具——MathType7.4免费版本!......
  • KMP算法实例——模式匹配
    题目描述:给定两个字符串,一个是文本串txt,另一个是模式串pat。请使用KMP算法找出模式串在文本串中的所有出现位置。示例输入:文本串 txt:"ABABDABACDABABCABAB"模式串 pat:"ABABCABAB"#include<stdio.h>#include<string.h>//计算模式串的最长公共前后缀数组voidco......
  • STM32中的DMA:解锁高效数据传输的秘密武器(内附实例)
    目录引言理解DMA:数据的高效搬运工DMA的主要特性多优先级请求事件标志数据对齐多样化的数据传输路径广泛的数据源与目标最大数据长度DMA寄存器详解增量与循环模式DMA中断机制​编辑小实验:DMA-ADC串口发送引言在现代嵌入式系统设计中,数据传输速度和效率是关键......
  • 什么是I2C,IIC怎么用,从实例波形分析I2C读写
    什么是I2C,IIC怎么用,从实例波形分析I2C读写前言今天分享的主题是I2C通信。接下来从I2C是什么,怎么用,以及以时钟外设读写作为实例进行分析。I2C简介I2C(Inter-IntegratedCircuit),也可以叫IIC、I2C,译作集成电路总线,是两线式串行通信总线,用于设备间的通讯等,标准情况下最高传送速率达......
  • C#开发单实例应用程序的几种方式
    C#默认的WinForm模板是不支持设置单实例的,也没有隔壁大哥VB.NET那样有个“生成单个实例应用程序”的勾选选项(VB某些时候要比C#更方便),实现单实例可以有多种方法:检测同名进程:Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName),如果集合的Length>1那就表明已......
  • Linux 基础命令实例教程
    Linux是一个强大的操作系统,掌握其基本命令对任何级别的用户来说都是至关重要的。本文将通过具体的实例来演示一些常用的Linux命令,帮助你更好地理解和运用它们。1.文件和目录操作例:列出当前目录下的所有文件和目录ls-la这会列出当前目录下所有文件和目录的详细信息......
  • C#开发单实例应用程序并响应后续进程启动参数
    C#默认的WinForm模板是不支持设置单实例的,也没有隔壁大哥VB.NET那样有个“生成单个实例应用程序”的勾选选项(VB某些时候要比C#更方便),实现单实例可以有多种方法:检测同名进程:Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName),如果集合的Length>1那就表明已......
  • 014文章解读与程序——中国电机工程学报,电力自动化设备EI\CSCD\北大核心《主动配 电
    ......