jenkins job配置脚本化

背景

job支持跨环境部署和迁移。

不能将job配置到一个固定的Jenkins系统中。

有两种方式支持脚本化管理配置。

Jenkinsfile

https://www.jenkins.io/doc/book/pipeline/getting-started/

As mentioned previously, Jenkins Pipeline is a suite of plugins that supports implementing and integrating continuous delivery pipelines into Jenkins. Pipeline provides an extensible set of tools for modeling simple-to-complex delivery pipelines "as code" via the Pipeline DSL. [1]

This section describes how to get started with creating your Pipeline project in Jenkins and introduces you to the various ways that a Jenkinsfile can be created and stored.

将配置参数和执行逻辑保存为Jenkinsfile,存储到git上。

https://www.jenkins.io/doc/book/pipeline/syntax/#parameters

pipeline {
    agent any
    parameters {
        string(name: 'PERSON', defaultValue: 'Mr Jenkins', description: 'Who should I say hello to?')

        text(name: 'BIOGRAPHY', defaultValue: '', description: 'Enter some information about the person')

        booleanParam(name: 'TOGGLE', defaultValue: true, description: 'Toggle this value')

        choice(name: 'CHOICE', choices: ['One', 'Two', 'Three'], description: 'Pick something')

        password(name: 'PASSWORD', defaultValue: 'SECRET', description: 'Enter a password')
    }
    stages {
        stage('Example') {
            steps {
                echo "Hello ${params.PERSON}"

                echo "Biography: ${params.BIOGRAPHY}"

                echo "Toggle: ${params.TOGGLE}"

                echo "Choice: ${params.CHOICE}"

                echo "Password: ${params.PASSWORD}"
            }
        }
    }
}

Jenkinsfile缺点

参数配置,必须在一次构建中生效。

但是有时候有不想运行业务逻辑, 只想将配置生效。

例如,只将gerrit triggers配置生效。

这样就有两种方法:

  • 1、JJB -- 后面单独介绍。
  • 2、将配置和业务逻辑写在一个jenkinsfile中, 在代码中使用分支控制。 使用输入参数进行控制分支。
  •    参考 https://stackoverflow.com/questions/44422691/how-to-force-jenkins-to-reload-a-jenkinsfile

Unfortunately the answer of TomDotTom was not working for me - I had the same issue and my jenkins required another stages unter 'Run Jenkinsfile' because of the following error:

Unknown stage section "stage". Starting with version 0.5, steps in a stage must be in a ‘steps’ block.

Also I am using params instead of parameters as variable to check the condition (as described in Jenkins Syntax).

当入参 params.Refresh == true, 不执行业务逻辑。

pipeline {
    agent any
    parameters {
        booleanParam(name: 'Refresh',
                    defaultValue: false,
                    description: 'Read Jenkinsfile and exit.')
    }
    stages {
        stage('Read Jenkinsfile') {
            when {
                expression { return params.Refresh == true }
            }
            steps {
              echo("stop")
            }
        }
        stage('Run Jenkinsfile') {
            when {
                expression { return params.Refresh == false }
            }
            stages {
              stage('Build') {
                  steps {
                    echo("build")
                  }
              }
              stage('Test') {
                  steps {
                    echo("test")
                  }
              }
              stage('Deploy') {
                  steps {
                    echo("deploy")
                  }
              }
            }
        }
    }
}

when 语法

只能应用于stage, 使用示例如下:

https://github.com/cvitter/jenkins-pipeline-examples/blob/master/Jenkinsfile-When

/ Jenkinsfile-When
// ----------------------------------------------------------------------
// This example shows a variety of ways to use 'when' for flow control
// Note: This Jenkinsfile needs to be executed as part of a
//       Multibranch Pipeline project to demonstrate the 'branch' 
//       variable in the stage("BASIC WHEN - Branch") stage
// ----------------------------------------------------------------------
pipeline {
   agent any
    
   environment {
      VALUE_ONE = '1'
      VALUE_TWO = '2'
      VALUE_THREE = '3'
   }
    
   stages {
      
      // Execute when branch = 'master'
      stage("BASIC WHEN - Branch") {
         when {
            branch 'master'
         }
         steps {
            echo 'BASIC WHEN - Master Branch!'
         }
      }
      
      // Expression based when example with AND
      stage('WHEN EXPRESSION with AND') {
         when {
            expression {
               VALUE_ONE == '1' && VALUE_THREE == '3'
            }
         }
         steps {
            echo 'WHEN with AND expression works!'
         }
      }
      
      // Expression based when example
      stage('WHEN EXPRESSION with OR') {
         when {
            expression {
               VALUE_ONE == '1' || VALUE_THREE == '2'
            }
         }
         steps {
            echo 'WHEN with OR expression works!'
         }
      }
      
      // When - AllOf Example
      stage("AllOf") {
        when {
            allOf {
                environment name:'VALUE_ONE', value: '1'
                environment name:'VALUE_TWO', value: '2'
            }
        }
        steps {
            echo "AllOf Works!!"
        }
      }
      
      // When - Not AnyOf Example
      stage("Not AnyOf") {
         when {
            not {
               anyOf {
                  branch "development"
                  environment name:'VALUE_TWO', value: '4'
               }
            }
         }
         steps {
            echo "Not AnyOf - Works!"
         }
      }
   }
}

JJB - jenkins-job-builder

https://docs.openstack.org/infra/jenkins-job-builder/index.html

Jenkins Job Builder takes simple descriptions of Jenkins jobs in YAML or JSON format and uses them to configure Jenkins. You can keep your job descriptions in human readable text format in a version control system to make changes and auditing easier. It also has a flexible template system, so creating many similarly configured jobs is easy.

To install:

$ pip install --user jenkins-job-builder

https://docs.openstack.org/infra/jenkins-job-builder/definition.html#job

- job-template:
    name: '{project-name}-verify'

    #####################
    # Variable Defaults #
    #####################

    branch: master

    #####################
    # Job Configuration #
    #####################

    parameters:
      - string:
          name: BRANCH
          default: '{branch}'

    scm:
      - git:
          refspec: 'refs/heads/{branch}'

https://stackoverflow.com/questions/44422691/how-to-force-jenkins-to-reload-a-jenkinsfile

- job:
      name: 'job-name'
      description: 'deploy template'
      concurrent: true
      properties:
        - build-discarder:
            days-to-keep: 7
        - rebuild:
            rebuild-disabled: false
      parameters:
        - choice:
            name: debug
            choices:
              - Y
              - N
            description: 'debug flag'
        - string:
            name: deploy_tag
            description: "tag to deploy, default to latest"
        - choice:
            name: deploy_env
            choices:
              - dev
              - test
              - preprod
              - prod
            description: "Environment"
      project-type: pipeline
      # you can use either DSL or pipeline SCM
      dsl: |
          node() {
             stage('info') {
               print params
             }
          }
      # pipeline-scm:
      #   script-path: Jenkinsfile
      #   scm:
      #     - git:
      #         branches:
      #           - master
      #         url: 'https://repository.url.net/x.git'
      #         credentials-id: 'jenkinsautomation'
      #         skip-tag: true
      #         wipe-workspace: false
      #   lightweight-checkout: true
出处:http://www.cnblogs.com/lightsong/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
原文地址:https://www.cnblogs.com/lightsong/p/14637448.html