首页 > 其他分享 >Jenkins: template

Jenkins: template

时间:2023-04-24 20:15:08浏览次数:40  
标签:description env currentBuild echo environment template Jenkins true

 

String workspace = "/opt/jenkins/workspace/${JOB_NAME}"
def v = 'v'
env.e1 = 'v1'

pipeline {
    agent {
        node {
            label 'master'
            customWorkspace "${workspace}"
        }
    }

    tools {
        git 'git'
        jdk 'jdk-19'
        maven 'maven'
    }

    options {
        ansiColor('xterm')
        buildDiscarder logRotator(artifactDaysToKeepStr: '60', artifactNumToKeepStr: '5', daysToKeepStr: '60', numToKeepStr: '5')
        checkoutToSubdirectory ''
        disableConcurrentBuilds abortPrevious: true
        disableResume()
        parallelsAlwaysFailFast()
        preserveStashes buildCount: 3
        quietPeriod 2  // unit: second
        retry 0
        skipDefaultCheckout(true)
        skipStagesAfterUnstable()
        timestamps()pod
        timeout(time: 1, unit: 'HOURS')
        warnError('warnError')
    }

    parameters {
        booleanParam defaultValue: true, description: 'description for boolean parameter', name: 'booleanParameter'
        choice choices: ['defaultChoice', 'choice1', 'choice2'], description: 'description for choice parameter', name: 'choiceParameter'
        file description: 'description for file parameter', name: 'data.zip'
        string defaultValue: 'defaultStringParameter', description: 'description', name: 'stringParameter', trim: true
    }

    // triggers {
    //     cron '''TZ=Europe/London
    //     H 0-9/2,18-23/2 1-30 1,2,3,9-10 1-5'''
    //     pollSCM '''TZ=Europe/London
    //     H 0-9/2,18-23/2 1-30 1,2,3,9-10 1-5'''
        // upstream 'folder-a/esoteric'
    //     upstream threshold: 'FAILURE', upstreamProjects: 'job-1, folder/job-2'  // default to only stable
    // }

    environment {  // 1. inside pipeline block
        e2 = 'v2'
        usernameWithPassword = credentials('08d73561-fb85-4796-b832-7a420b40f19c')  // he environment variable specified will be set to username:password and two additional environment variables will be automatically defined: MYVARNAME_USR and MYVARNAME_PSW respectively.
        sshUsernameWithPrivatekey = credentials('f15a044c-c823-4119-8373-dc0c0d86963d')  // the environment variable specified will be set to the location of the SSH key file that is temporarily created and two additional environment variables will be automatically defined: MYVARNAME_USR and MYVARNAME_PSW (holding the passphrase).
        secretText = credentials('baef090a-a4c3-4dae-a826-a5fef073a8fc')  // the environment variable specified will be set to the Secret Text content
        secretFile = credentials('61467172-bb10-4ee4-a9a5-eb64d171f2ad')  // the environment variable specified will be set to the location of the File file that is temporarily created
    }

    stages {
        stage('----------------------------------------Environment----------------------------------------') {
            input {
                message 'Input Message'
                ok 'Yes, we should.'
                submitterParameter 'submitter'
                parameters {
                    string defaultValue: 'defaultInputStringParameter', description: 'description for input string parameter', name: 'inputStringParameter', trim: true
                }
            }
            environment {  // 2. inside stage directive
                e3 = 'v3'
            }
            steps {
                cleanWs(notFailBuild: true)
                checkout scmGit(branches: [[name: 'refs/heads/mainn']], browser: github('https://github.com/annexationer/eschew'), extensions: [checkoutOption(5), cloneOption(depth: 1, honorRefspec: true, noTags: false, reference: '', shallow: true, timeout: 5), [$class: 'ScmName', name: 'IKEA'], buildSingleRevisionOnly()], userRemoteConfigs: [[credentialsId: 'f15a044c-c823-4119-8373-dc0c0d86963d', name: 'upstream', refspec: '+refs/heads/main:refs/remotes/upstream/mainn +refs/heads/dev:refs/remotes/upstream/devv', url: '[email protected]:annexationer/eschew.git']])
                withEnv(["e1=${JENKINS_URL}", "e2=${JOB_URL}", "e3=${BUILD_URL}"]) {  // can override any env variables
                        sh '''
                            env | sort

                            echo ${usernameWithPassword} > usernameWithPassword
                            echo ${usernameWithPassword_USR} >> usernameWithPassword
                            echo ${usernameWithPassword_PSW} >> usernameWithPassword

                            echo ${sshUsernameWithPrivatekey} > sshUsernameWithPrivatekey
                            echo ${sshUsernameWithPrivatekey_USR} >> sshUsernameWithPrivatekey
                            echo ${sshUsernameWithPrivatekey_PSW} >> sshUsernameWithPrivatekey

                            echo ${secretText} > secretText
                            
                            echo ${secretFile} > secretFile
                            
                            ls -ahl

                            mvn --version
                            java -version
                            javac -version

                        '''
                }

                script {  // should only in the steps 
                    env.e1 = "${JOB_NAME}"  // folder-a/esoteric, override scriptted env
                    env.e2 = "${JOB_BASE_NAME}"  // esoteric, cannot override declarative env
                    env.e3 = "${BUILD_ID}"  // cannot override declarative env, but since e3 declare in this stage, following stage can access e3
                    def var1 = sh encoding: 'UTF-8', returnStdout: true, script: '''#!/usr/bin/env -vS bash
                        ls -ahl'''
                    var1 = var1.trim()
                    echo ">> var1 = ${var1} <<"
                    String var2 = "${env.WORKSPACE}"  // ${JENKINS_HOME}/workspace/folder-a/esoteric
                    var3 = "${env.GIT_LOCAL_BRANCH}"
                    sh '''
                        env | sort
                    '''
                }
            }
        }
        
        stage('----------------------------------------Check----------------------------------------') {
            steps {
                timeout(time: 5, unit: 'MINUTES') {
                    script {
                        echo ">> var3 = ${var3} <<"
                        sh '''
                            env | sort
                            ls -ahl
                        '''
                        config = readFile(encoding: 'Base64', file: '.git/config').trim()
                    }
                }
            }
        }

        stage('----------------------------------------Build----------------------------------------') {
            steps {
                timeout(time: 20, unit: 'MINUTES') {
                    script {
                        if (env.GIT_COMMIT) {
                            echo "GIT_COMMIT = ${GIT_COMMIT}"
                        }
                        echo "${config}"
                        def exitStatus = sh encoding: 'UTF-8', returnStatus: true, script: 'command_not_exist'
                        if (exitStatus != 0) {
                            println '\033[7mcommand failed\033[0m'
                        }
                        echo "${currentBuild.getBuildCauses()}"
                        currentBuild.getBuildCauses().each {
                            println it
                        }
                    }
                }
            }
        }

        stage('----------------------------------------Deploy----------------------------------------') {
            agent {
                label "master"
                customWorkspace "${workspace}"
            }
            when {
                beforeAgent true
                beforeInput true
                beforeOptions true
                triggeredBy cause: "UserIdCause", detail: "jenkins"
                expression { env.JOB_BASE_NAME ==~ /(production|staging|esoteric)/ }
                expression { env.NODE_NAME != null }
                anyOf {
                    branch 'main'
                    environment name: 'CI', value: 'true'
                    environment name: 'DEPLOY_TO', value: 'production'
                    environment name: 'DEPLOY_TO', value: 'staging'
                }
           
            }
            steps {
                timeout(time: 20, unit: 'MINUTES') {
                    script {
                        if (env.GIT_BRANCH) {
                            echo "GIT_BRANCH = ${GIT_BRANCH}"
                        }
                    }
                }
            }
        }

        stage('----------------------------------------Parallel----------------------------------------') {
            parallel {
                stage('----------------------------------------Parallel-1----------------------------------------') {
                    steps {
                        script {
                            def browsers = ['chrome', 'firefox']
                            for ( int i = 0; i  < browsers.size(); ++i) {
                                println browsers[i]
                            }
                            browsers.add('edge')
                            browsers.each {
                                print it
                            }
                            // browsers.removeElement('edge')
                            browsers -= 'edge'
                            println browsers.join(', ')
                        }
                    }
                }
                stage('----------------------------------------Parallel-2----------------------------------------') {
                    steps {
                        // error(message: 'Error Signal')  // no strack trace throw new Exception("Error Signal")
                        script {
                            def list1 = [2,1,3,4,5,6,76]
                            list1.findAll { it > 3 }
                            def list2 = ["Hello", "World"]
                        }
                    }
                }
            }
        }
    }

    post {
        always {
            script {
                println('post: always')
                if (env.WORKSPACE != null) {
                    println "WORKSPACE = ${WORKSPACE}"
                } else {
                    println 'WORKSPACE is null'
                }
            }
        }
        success {
            script {
                if (currentBuild.description) {
                    currentBuild.description += 'post: success'
                } else {
                    currentBuild.description = 'post: success'
                }
            }
        }
        failure {
            script {
                 if (currentBuild.description) {
                    currentBuild.description += 'post: failure'
                } else {
                    currentBuild.description = 'post: failure'
                }
            }
        }
        aborted {
            script {
                 if (currentBuild.description) {
                    currentBuild.description += 'post: aborted'
                } else {
                    currentBuild.description = 'post: aborted'
                }
            }
        }
    }
}

 

标签:description,env,currentBuild,echo,environment,template,Jenkins,true
From: https://www.cnblogs.com/dissipate/p/17350702.html

相关文章

  • No qualifying bean of type 'org.apache.rocketmq.spring.core.RocketMQTemplate' av
    2023-04-2418:50:39.372WARN26732---[main]ConfigServletWebServerApplicationContext:Exceptionencounteredduringcontextinitialization-cancellingrefreshattempt:org.springframework.beans.factory.BeanCreationException:Errorcreating......
  • Django4全栈进阶之路16 template模板的基础模板
    <!DOCTYPEhtml><html><head><metacharset="UTF-8"><title>{%blocktitle%}MySite{%endblock%}</title>{%blockstyles%}{%endblock%}</head><body><header><h1>MySite</h......
  • Django4全栈进阶之路13 template模板
    在Django4中,模板是用于生成HTML响应的文件。模板将动态数据和静态HTML组合在一起,以便最终呈现给用户的页面。Django4中的模板使用Django模板语言(DjangoTemplateLanguage,简称DT)编写。DT与HTML类似,但包含一些特殊的标记和语法,用于动态地生成HTML内容。以下是一......
  • Jenkins使用备注
    Jenkins2.361.1(LTS)版本下载官网下载地址:https://www.jenkins.io/download/启动配置1.配置JDK112.配置服务端口--httpPort=90903.配置JENKINS_HOME,用于修改Jenkins存储与配置的目录启动命令重新设置Jenkins的存储与配置目录,setJENKINS_HOME=my-jenkins-configjava-jar......
  • 在服务器上安装jenkins
    jenkins.warjdk-8u131-linux-x64.tarapache-tomcat-7.0.68.tar上传服务器上述安装包,安装好jdk,tomcat,验证是否安装成功,然后把tomcat/webapps/ROOT目录里的文件都删除掉,把jenkins.war拷贝到ROOT目录下,然后解压jar-xvfjenkins.war。然后返回tomcat/conf目录中,编辑server.xml......
  • vue-admin-template 如何添加快捷导航(标签导航栏)
    前言关于快捷导航(标签栏导航)在文档中确实有介绍,但是看完是一头雾水,不知道如何修改,不过文档最后给了一个移除的大致操作,从这里可以找到入手点前期准备vue-admin-template项目代码vue-element-admin项目代码操作流程注:以下操作流程是按照自行摸索的操作顺序来写的,因此......
  • 在Linux服务器上装jenkins
    官网下载jenkinshttps://www.jenkins.io/zh/download/下载的文件是jenkins.war把安装文件放到Linux中 可以直接在远程连接中上传文件,也可以使用宝塔面板上传,还可以使用Xftp上传 安装jenkinscd进入存放安装文件的目的,使用命令安装java-jarjenkins.war--httpPort=8080......
  • SpringDataRedis的序列化方式和StringRedisTemplate手动序列化详解
    一.SpringDataRedis之前新创建一个Spring项目,在进行配置完成redis和common-pool依赖:1.引入依赖redis:<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis-reactive</artifactId></dependency>......
  • 11、集群外部、内部的jenkins如何在k8s集群上创建动态pod agent
    Kubernetes插件能够让JenkinsMaster在Kubernetes集群上运行基于Pod的动态Agent◼它会为启动的每个Agent创建一个Pod,并在运行完成后停止它◼各PodAgent以InboundAgent形式运行,inbound-agent容器会自动连接到JenkinsMaster◆这意味着在每个PodAgent中,始终有一......
  • jenkins部署(最新版)
     jenkins中文社区https://www.jenkins.io/zh/doc/book/installing/1、系统管理        #邮件内容模板文档:https://blog.csdn.net/J_____Q/article/details/118518554    #进行邮件测试,看是否可以收到邮件  #邮箱收件 ......