Skip to content

声明式流水线(Declarative Pipeline)

声明式流水线在流水线子系统中引入了一种更简单、更有表现力的语法,基于 Groovy 的 DSL(领域特定语言),提供了一种更简洁、更易于使用和阅读的方式来定义流水线。要使用它们,请安装 Pipeline:Declarative Plugin 插件。

所有有效的声明式流水线必须包含在 pipeline 块中,例如:

groovy
pipeline {
    /* 在这里插入声明式流水线 */
}

在声明式流水线中有效的基本语句和表达式遵循与 Groovy 相同的语法规则,但有以下例外:

  • 流水线的顶层必须是一个块,具体为:Pipeline{}
  • 不使用分号作为语句分隔符。每个语句都必须在自己的行上。
  • 块只能由节、指令、步骤或赋值语句组成。
  • 属性引用语句被视为无参数方法调用。例如,input 被视为 input()

官网 - Declarative Pipeline

节(Section)

声明式流水线中的节(Section)通常包含一个或多个指令或步骤。

agent

agent 部分用于指定在哪个节点上执行流水线或特定的阶段(stage)。它是每个 Pipeline 的核心组件,允许你定义构建所需的环境(如 Docker、特定的节点、标签等)。通过 agent,你可以控制代码构建、测试和部署的执行环境。

基本语法

groovy
pipeline {
    agent any  // 在任何可用的节点上执行
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
    }
}

agent 指令的不同类型

  1. any

使用 any,Pipeline 可以在任何可用的 Jenkins 节点上执行。

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building on any available agent'
            }
        }
    }
}
  1. none

使用 none,表示该 Pipeline 不会在任何节点上执行。通常用于定义只包含 stage 的 Pipeline。

groovy
pipeline {
    agent none
    stages {
        stage('Build') {
            agent any  // 单独为此阶段定义执行节点
            steps {
                echo 'Building...'
            }
        }
    }
}
  1. 指定标签

可以指定一个标签,Pipeline 将在具有该标签的节点上执行。这对于在特定环境中执行构建很有用。

groovy
pipeline {
    agent { label 'linux' }  // 在具有 'linux' 标签的节点上执行
    stages {
        stage('Build') {
            steps {
                echo 'Building on a Linux node'
            }
        }
    }
}
  1. 指定节点名称

你可以直接指定节点名称,以确保在特定的 Jenkins 节点上执行。

groovy
pipeline {
    agent { node { label 'my-node' } }  // 在名为 'my-node' 的节点上执行
    stages {
        stage('Build') {
            steps {
                echo 'Building on a specific node'
            }
        }
    }
}
  1. Docker 容器

可以在 Docker 容器中运行 Pipeline。通过 Docker,你可以指定一个基础镜像,并在其中执行构建步骤。

groovy
pipeline {
    agent {
        docker {
            image 'node:14'  // 使用 Node.js 14 的 Docker 镜像
            args '-v /tmp:/tmp'  // 传递 Docker 启动参数
        }
    }
    stages {
        stage('Build') {
            steps {
                sh 'npm install'  // 在 Docker 容器内执行
            }
        }
    }
}
  1. 使用 Dockerfile

你还可以从自定义的 Dockerfile 构建容器。

groovy
pipeline {
    agent {
        dockerfile {
            dir 'docker'  // Dockerfile 目录
            filename 'Dockerfile'  // Dockerfile 文件名
            additionalBuildArgs '--build-arg MY_ARG=value'  // 额外的构建参数
        }
    }
    stages {
        stage('Build') {
            steps {
                sh 'npm install'  // 在自定义容器中执行
            }
        }
    }
}

例子

  1. 基本 Pipeline
groovy
pipeline {
    agent any  // 在任何可用的节点上执行
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
        stage('Test') {
            steps {
                echo 'Testing...'
            }
        }
    }
}
  1. 在特定标签节点上执行
groovy
pipeline {
    agent { label 'windows' }  // 在 Windows 节点上执行
    stages {
        stage('Build') {
            steps {
                echo 'Building on Windows node...'
            }
        }
    }
}
  1. 在 Docker 容器中执行
groovy
pipeline {
    agent {
        docker { image 'python:3.8' }  // 在 Python 3.8 的 Docker 容器中执行
    }
    stages {
        stage('Build') {
            steps {
                sh 'pip install -r requirements.txt'  // 在 Docker 容器中执行
            }
        }
    }
}

post

post 指令用于定义在 Pipeline 或特定阶段(stage)完成后需要执行的步骤。它通常用于处理构建完成后的清理、通知、结果记录等操作。post 指令的主要作用是增强流水线的健壮性,并确保某些重要操作在构建结束后始终执行。

基本语法

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
    }
    post {
        always {
            echo 'This will always run after the stages.'
        }
        success {
            echo 'This will run only if the pipeline succeeds.'
        }
        failure {
            echo 'This will run only if the pipeline fails.'
        }
        unstable {
            echo 'This will run only if the pipeline is unstable.'
        }
        changed {
            echo 'This will run only if the current build is different from the previous one.'
        }
    }
}

post 指令的关键部分

  1. always

无论流水线成功或失败,always 块中的步骤都会执行。通常用于清理、记录日志或发送通知。

groovy
post {
    always {
        echo 'Cleanup actions go here.'
    }
}
  1. success

只有当流水线成功完成时,success 块中的步骤才会执行。适用于发送成功通知或执行后续操作。

groovy
post {
    success {
        echo 'The build was successful!'
    }
}
  1. failure

只有在流水线失败时,failure 块中的步骤才会执行。通常用于发送失败通知或执行错误处理。

groovy
post {
    failure {
        echo 'The build failed!'
    }
}
  1. unstable

当流水线的构建状态标记为不稳定时(例如,某些测试失败但其他测试通过),unstable 块中的步骤将执行。

groovy
post {
    unstable {
        echo 'The build is unstable!'
    }
}
  1. changed

只有当当前构建与上一个构建的结果不同(成功、失败或不稳定)时,changed 块中的步骤才会执行。

groovy
post {
    changed {
        echo 'The build result has changed since the last build!'
    }
}

组合使用示例

可以将多个 post 块结合使用,以便在不同情况下执行不同的操作。

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
    }
    post {
        always {
            echo 'Cleaning up...'
        }
        success {
            echo 'Build succeeded!'
        }
        failure {
            echo 'Build failed!'
        }
        unstable {
            echo 'Build is unstable!'
        }
        changed {
            echo 'Build result has changed!'
        }
    }
}

进阶用法

  1. 带参数的步骤

post 块中的步骤可以使用环境变量、参数或其他方法,使得脚本更具灵活性。

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                script {
                    env.BUILD_STATUS = currentBuild.result ?: 'SUCCESS'
                }
                echo 'Building...'
            }
        }
    }
    post {
        always {
            echo "Build finished with status: ${env.BUILD_STATUS}"
        }
    }
}
  1. 在特定阶段中使用 post

可以在特定的 stage 中定义 post 块,只在该阶段结束后执行。

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
            post {
                success {
                    echo 'Build stage succeeded!'
                }
                failure {
                    echo 'Build stage failed!'
                }
            }
        }
        stage('Test') {
            steps {
                echo 'Testing...'
            }
        }
    }
    post {
        always {
            echo 'This runs after all stages.'
        }
    }
}

stages

包含一个或多个阶段指令的序列,stages 部分是管道描述的大部分"工作"的位置。建议 stages 至少包含一个阶段指令,用于持续交付流程的每个离散部分,例如构建、测试和部署。

groovy
pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                echo 'Hello World'
            }
        }
    }
}

steps

stages 指令用于定义流水线的多个阶段(stage)。每个阶段代表流水线中的一个特定步骤,例如构建、测试或部署。通过将流水线拆分为多个阶段,能够更清晰地组织和管理构建过程,并在 Jenkins UI 中提供可视化反馈。

基本语法

groovy
pipeline {
    agent any  // 可以在任何可用的节点上执行
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
        stage('Test') {
            steps {
                echo 'Testing...'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying...'
            }
        }
    }
}

关键要素

  1. 每个阶段的结构

每个阶段通常包含以下几个部分:

  • stage:定义阶段的名称。
  • steps:在该阶段中执行的具体操作。
  • environment:可选,定义该阶段的环境变量。
groovy
stage('Build') {
    steps {
        // 具体操作
    }
}
  1. 顺序执行

stages 中定义的阶段按顺序依次执行。每个阶段可以依赖于上一个阶段的结果。

  1. 并行执行

可以在同一个流水线中定义并行执行的阶段,这样多个阶段可以同时运行,从而提高构建速度。使用 parallel 指令来实现。

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
        stage('Test') {
            parallel {
                stage('Unit Tests') {
                    steps {
                        echo 'Running unit tests...'
                    }
                }
                stage('Integration Tests') {
                    steps {
                        echo 'Running integration tests...'
                    }
                }
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying...'
            }
        }
    }
}
  1. 使用环境变量

在某些阶段中,可以定义特定的环境变量,这些变量只在该阶段有效。

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            environment {
                MY_VAR = 'some value'
            }
            steps {
                echo "The value of MY_VAR is ${env.MY_VAR}"
            }
        }
    }
}
  1. 添加条件

可以结合 when 指令,在特定条件下执行某个阶段。这样可以根据分支、环境变量或其他条件灵活控制构建过程。

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
        stage('Test') {
            when {
                branch 'main'
            }
            steps {
                echo 'Testing on main branch...'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying...'
            }
        }
    }
}

示例

  1. 基本 Pipeline 示例
groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building the application...'
            }
        }
        stage('Test') {
            steps {
                echo 'Running tests...'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying the application...'
            }
        }
    }
}
  1. 使用并行阶段
groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building the application...'
            }
        }
        stage('Test') {
            parallel {
                stage('Unit Tests') {
                    steps {
                        echo 'Running unit tests...'
                    }
                }
                stage('Integration Tests') {
                    steps {
                        echo 'Running integration tests...'
                    }
                }
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying the application...'
            }
        }
    }
}
  1. 在条件下执行阶段
groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building the application...'
            }
        }
        stage('Test') {
            when {
                branch 'develop'
            }
            steps {
                echo 'Running tests on the develop branch...'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying the application...'
            }
        }
    }
}

指令(Directive)

environment

environment 指令用于定义环境变量,这些变量在 Pipeline 的某些或所有阶段中都可以使用。environment 指令可以放在 pipeline 的不同层级,作用范围从全局到局部(单个阶段)。通过设置环境变量,可以为构建过程中的不同任务提供灵活的参数控制。

  • 全局环境变量:在 pipeline 块中定义的环境变量,在所有阶段中都可以使用。
  • 局部环境变量:在 stage 块中定义的环境变量,只在该阶段内部有效。
  • env 对象:通过 env.ENV_VAR_NAME 访问环境变量。

以下是一个简单的 environment 指令的示例:

groovy
pipeline {
    agent any
    environment {
        // 定义全局环境变量
        JAVA_HOME = '/usr/lib/jvm/java-11-openjdk'
        NODE_ENV = 'production'
        MY_ENV_VAR = 'some_value'
    }
    stages {
        stage('Build') {
            steps {
                echo "JAVA_HOME is set to: ${env.JAVA_HOME}"
                echo "NODE_ENV is set to: ${env.NODE_ENV}"
            }
        }
        stage('Test') {
            environment {
                // 在这个阶段定义局部环境变量
                TEST_ENV_VAR = 'test_value'
            }
            steps {
                echo "TEST_ENV_VAR is set to: ${env.TEST_ENV_VAR}"
            }
        }
    }
}

options

options 指令用于设置 pipeline 或 stage 的各种行为参数,例如超时时间、并发执行限制等。通过 options 指令可以增强 pipeline 的控制性、可靠性和灵活性。

以下是常见的 options 指令及其用途:

  1. timeout

设置流水线或阶段的最大执行时间,超时后将终止执行。

groovy
pipeline {
    agent any
    options {
        timeout(time: 1, unit: 'HOURS')  // 设置为1小时超时
    }
    stages {
        stage('Example') {
            steps {
                echo 'Hello, World!'
            }
        }
    }
}
  1. timestamps

为每个步骤输出添加时间戳,方便调试和日志查看。

groovy
pipeline {
    agent any
    options {
        timestamps()  // 开启时间戳
    }
    stages {
        stage('Example') {
            steps {
                echo 'Hello, World!'
            }
        }
    }
}
  1. retry

设置流水线或阶段的失败重试次数。

groovy
pipeline {
    agent any
    options {
        retry(3)  // 失败时重试3次
    }
    stages {
        stage('Example') {
            steps {
                echo 'Hello, World!'
            }
        }
    }
}
  1. disableConcurrentBuilds

禁止同一个 pipeline 并发执行,避免多个实例同时运行带来的冲突。

groovy
pipeline {
    agent any
    options {
        disableConcurrentBuilds()  // 禁止并发构建
    }
    stages {
        stage('Example') {
            steps {
                echo 'Hello, World!'
            }
        }
    }
}
  1. buildDiscarder

自动丢弃旧的构建记录,以节省存储空间。

groovy
pipeline {
    agent any
    options {
        buildDiscarder(logRotator(numToKeepStr: '5', artifactNumToKeepStr: '2'))  // 保留5个构建记录,2个构件
    }
    stages {
        stage('Example') {
            steps {
                echo 'Hello, World!'
            }
        }
    }
}
  1. skipStagesAfterUnstable

如果构建结果为 UNSTABLE,跳过后续阶段。

groovy
pipeline {
    agent any
    options {
        skipStagesAfterUnstable()  // 构建结果为UNSTABLE时跳过后续阶段
    }
    stages {
        stage('Example') {
            steps {
                echo 'Hello, World!'
            }
        }
    }
}
  1. quietPeriod

设置在构建开始之前等待的时间(单位:秒)。

groovy
pipeline {
    agent any
    options {
        quietPeriod(10)  // 构建前等待10秒
    }
    stages {
        stage('Example') {
            steps {
                echo 'Hello, World!'
            }
        }
    }
}
  1. newContainerPerStage

在每个 stage 中运行新的容器(用于 Docker pipelines)。

groovy
pipeline {
    agent any
    options {
        newContainerPerStage()  // 每个stage运行新的容器
    }
    stages {
        stage('Example') {
            steps {
                echo 'Running in a new container per stage'
            }
        }
    }
}

parameters

parameters 指令用于定义构建时的输入参数。这些参数允许用户在触发构建时进行配置,从而让 Pipeline 更加灵活和动态化。你可以通过不同的参数类型(如字符串、布尔值、选择项等)来传递信息给 Pipeline。

以下是一些常见的 parameters 指令示例:

  1. string 参数

用于接受用户输入的字符串类型参数。

groovy
pipeline {
    agent any
    parameters {
        string(name: 'BRANCH_NAME', defaultValue: 'main', description: 'Which Git branch to build?')
    }
    stages {
        stage('Build') {
            steps {
                echo "Building branch: ${params.BRANCH_NAME}"
            }
        }
    }
}
  1. booleanParam 参数

用于接受布尔值(true/false)的参数,通常用于控制某些构建步骤的开关。

groovy
pipeline {
    agent any
    parameters {
        booleanParam(name: 'RUN_TESTS', defaultValue: true, description: 'Run tests?')
    }
    stages {
        stage('Build') {
            steps {
                echo "Run tests: ${params.RUN_TESTS}"
                if (params.RUN_TESTS) {
                    echo 'Running tests...'
                }
            }
        }
    }
}
  1. choice 参数

允许用户从预定义的多个选项中进行选择。

groovy
pipeline {
    agent any
    parameters {
        choice(name: 'DEPLOY_ENV', choices: ['development', 'staging', 'production'], description: 'Select deployment environment')
    }
    stages {
        stage('Deploy') {
            steps {
                echo "Deploying to environment: ${params.DEPLOY_ENV}"
            }
        }
    }
}
  1. password 参数

用于安全输入,例如密码,不会在日志中明文显示。

groovy
pipeline {
    agent any
    parameters {
        password(name: 'DB_PASSWORD', defaultValue: '', description: 'Database password')
    }
    stages {
        stage('Deploy') {
            steps {
                echo "Using provided database password (hidden in logs)"
                // 密码不会被明文显示
            }
        }
    }
}
  1. text 参数

用于接受多行文本输入。

groovy
pipeline {
    agent any
    parameters {
        text(name: 'RELEASE_NOTES', defaultValue: '', description: 'Enter release notes')
    }
    stages {
        stage('Release') {
            steps {
                echo "Release notes: ${params.RELEASE_NOTES}"
            }
        }
    }
}
  1. file 参数

允许用户在构建时上传文件,文件可以在 Pipeline 中使用。

groovy
pipeline {
    agent any
    parameters {
        file(name: 'CONFIG_FILE', description: 'Upload a configuration file')
    }
    stages {
        stage('Process File') {
            steps {
                echo "Processing file: ${params.CONFIG_FILE}"
                // 在这里可以使用上传的文件
            }
        }
    }
}
  1. run 参数

用于选择之前的某个构建作为参数。

groovy
pipeline {
    agent any
    parameters {
        run(name: 'PREVIOUS_BUILD', description: 'Select previous build', filter: 'SUCCESSFUL')
    }
    stages {
        stage('Checkout') {
            steps {
                echo "Using previous build: ${params.PREVIOUS_BUILD}"
            }
        }
    }
}
  1. choiceParameter 参数(扩展插件)

允许动态生成选择参数(需要插件支持)。

groovy
pipeline {
    agent any
    parameters {
        choiceParameter(name: 'DYNAMIC_CHOICE', script: 'return ["option1", "option2", "option3"]')
    }
    stages {
        stage('Choose') {
            steps {
                echo "Selected option: ${params.DYNAMIC_CHOICE}"
            }
        }
    }
}

triggers

triggers 指令用于定义触发构建的条件。通过 triggers,你可以配置定时触发、基于 GitHub 事件的触发或其他事件驱动的触发器,这样当满足条件时,Jenkins 会自动启动一个新的构建。

以下是常见的 triggers 指令及其用途:

  1. cron(定时触发)

cron 是 Jenkins 中常用的定时触发机制,按照指定的时间间隔自动触发构建。时间格式类似于 Linux 的 cron 表达式。

groovy
pipeline {
    agent any
    triggers {
        cron('H 4 * * 1-5')  // 每个工作日的凌晨4点触发构建
    }
    stages {
        stage('Build') {
            steps {
                echo 'Building project...'
            }
        }
    }
}
  • H 表示 Jenkins 会智能选择一个散列的时间,避免集群中所有作业同时执行。
  • 例子 H 4 * * 1-5 表示每周一到周五的凌晨4点执行。
  1. pollSCM(SCM 轮询触发)

pollSCM 会定期检查版本控制系统(如 Git)是否有新的更改,如果有更改,则触发构建。它也是基于 cron 的时间格式。

groovy
pipeline {
    agent any
    triggers {
        pollSCM('H/15 * * * *')  // 每15分钟检查一次SCM是否有更改
    }
    stages {
        stage('Build') {
            steps {
                echo 'Polling SCM and building project...'
            }
        }
    }
}
  • H/15 * * * * 表示每15分钟检查一次。
  1. upstream(上游触发)

上游项目的构建成功后,自动触发下游项目的构建。

groovy
pipeline {
    agent any
    triggers {
        upstream(upstreamProjects: 'UpstreamJob', threshold: hudson.model.Result.SUCCESS)  // 当 "UpstreamJob" 成功时触发构建
    }
    stages {
        stage('Build') {
            steps {
                echo 'Triggered by upstream job'
            }
        }
    }
}
  • upstreamProjects 参数指定上游的项目名称。
  • threshold 可以设置触发构建的条件(如成功或失败时)。
  1. githubPush(GitHub 推送触发)

当 GitHub 仓库有新的推送时自动触发构建。这个触发器通常需要在 Jenkins 中安装 GitHub 插件,并配置 Webhook。

groovy
pipeline {
    agent any
    triggers {
        githubPush()  // GitHub推送时触发构建
    }
    stages {
        stage('Build') {
            steps {
                echo 'Triggered by GitHub push'
            }
        }
    }
}
  1. gitlab(GitLab 推送和合并请求触发)

类似于 githubPushgitlab 触发器会根据 GitLab 事件(如推送、合并请求)触发构建。需要安装 GitLab 插件并配置 Webhook。

groovy
pipeline {
    agent any
    triggers {
        gitlab(triggerOnPush: true, triggerOnMergeRequest: true, branchFilterType: "All")  // GitLab推送或合并请求时触发
    }
    stages {
        stage('Build') {
            steps {
                echo 'Triggered by GitLab event'
            }
        }
    }
}
  1. generic(通用Webhook触发)

通用 Webhook 触发器,适用于配置自定义 Webhook 事件(例如从其他系统发送的 HTTP 请求)。

groovy
pipeline {
    agent any
    triggers {
        genericTrigger(
            causeString: 'Triggered on external event',
            token: 'your-webhook-token',  // 自定义的 webhook token
            printContributedVariables: true,
            printPostContent: true,
            silentResponse: false
        )
    }
    stages {
        stage('Build') {
            steps {
                echo 'Triggered by a generic webhook'
            }
        }
    }
}
  • token 是用于验证 Webhook 的自定义令牌。
  1. bitbucketPush(Bitbucket 推送触发)

在 Bitbucket 仓库中有新的推送时触发构建。需要安装 Bitbucket 插件并配置 Webhook。

groovy
pipeline {
    agent any
    triggers {
        bitbucketPush()  // Bitbucket推送时触发构建
    }
    stages {
        stage('Build') {
            steps {
                echo 'Triggered by Bitbucket push'
            }
        }
    }
}
  1. issueCommentTrigger(评论触发)

当在版本控制系统中某个提交或合并请求上添加特定的评论时,触发构建。

groovy
pipeline {
    agent any
    triggers {
        issueCommentTrigger('rebuild')  // 当检测到 "rebuild" 评论时触发构建
    }
    stages {
        stage('Build') {
            steps {
                echo 'Triggered by issue comment'
            }
        }
    }
}

Jenkins cron syntax

Jenkins 中的 cron 语法用于定义定时任务的触发规则,类似于 Linux 系统中的 cron 表达式。其格式为 5 个空格分隔的字段,每个字段对应一个时间单位。具体语法如下:

MINUTE HOUR DOM MONTH DOW

每个字段的含义:

  • MINUTE:分钟 (0 - 59)
  • HOUR:小时 (0 - 23)
  • DOM:日期中的哪一天 (1 - 31)
  • MONTH:月份 (1 - 12) 或者使用缩写如 JAN, FEB 等
  • DOW:星期几 (0 - 7) (0 或 7 代表星期日) 或者使用缩写如 SUN, MON 等

常用符号说明

  • *:表示 "每个" 单位的时间。例如 * 在 MINUTE 字段中表示每分钟。
  • H:表示 "散列",Jenkins 会为不同的任务自动计算一个值,避免所有任务同时运行。
  • ,:用来分隔多个值。例如 MON,WED,FRI 表示星期一、三、五。
  • -:指定范围。例如 1-5 在 DOW 字段中表示星期一到星期五。
  • /:指定步长。例如 H/15 表示每隔 15 分钟触发一次。
  • ?:只能用在 DOM 和 DOW 字段中,表示不关心的值(例如你在 DOM 中填写了具体的日期,DOW 中可以用 ?)。

示例解释

  1. 每隔 15 分钟执行一次

    groovy
    H/15 * * * *
    • H/15 表示从 Jenkins 自动选择的某个时间点开始,每隔 15 分钟执行一次。
  2. 每天凌晨 2 点执行

    groovy
    0 2 * * *
    • 0 表示第 0 分钟,即整点。
    • 2 表示 2 点钟。
  3. 每个工作日的凌晨 4 点执行

    groovy
    0 4 * * 1-5
    • 1-5 表示星期一到星期五。
  4. 每月的 1 号和 15 号的凌晨 3 点执行

    groovy
    0 3 1,15 * *
    • 1,15 表示每月的 1 号和 15 号。
  5. 每周三中午 12 点执行

    groovy
    0 12 * * WED
    • WED 表示星期三。
  6. 每周一到周五的随机时间执行

    groovy
    H H * * 1-5
    • H 表示 Jenkins 为每个 job 选择一个随机时间,但不会与其他 job 同时触发。
  7. 每周末的凌晨 1 点执行

    groovy
    0 1 * * 6,0
    • 6,0 表示星期六和星期日。

stage

stage 指令用于定义流水线中的不同阶段(stage),每个阶段表示流水线中的一个逻辑步骤。stage 可以包含多个构建步骤,通过清晰的阶段划分,便于流水线的组织和维护。每个 stage 也可以进行并行化、超时、条件控制等操作。

基本语法

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
        stage('Test') {
            steps {
                echo 'Testing...'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying...'
            }
        }
    }
}

关键点

  1. stages: 这是一个用于包裹多个 stage 的容器。
  2. stage: 每个 stage 表示一个流水线的独立阶段,可以包含多个 steps(具体执行的步骤)。
  3. steps: 包含执行构建操作的具体步骤,比如 shell 命令、编译、测试等。

stage 常用功能

  1. 条件控制 when

可以通过 when 指令来控制阶段是否执行。

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
        stage('Deploy to Production') {
            when {
                branch 'main'  // 只有在 main 分支时执行
            }
            steps {
                echo 'Deploying to production...'
            }
        }
    }
}
  1. 并行执行 parallel

可以通过 parallel 指令在同一阶段中并行执行多个步骤,通常用于加速流水线的执行。

groovy
pipeline {
    agent any
    stages {
        stage('Tests') {
            parallel {
                stage('Unit Tests') {
                    steps {
                        echo 'Running unit tests...'
                    }
                }
                stage('Integration Tests') {
                    steps {
                        echo 'Running integration tests...'
                    }
                }
            }
        }
    }
}
  1. 超时 timeout

为某个阶段设置执行时间限制,如果超时则终止该阶段。

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
        stage('Test') {
            options {
                timeout(time: 5, unit: 'MINUTES')  // 测试阶段超时限制为5分钟
            }
            steps {
                echo 'Testing...'
            }
        }
    }
}
  1. 串行和并行 stage 结合使用

可以灵活组合串行和并行 stage,以优化流水线的执行。

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
        stage('Tests') {
            parallel {
                stage('Unit Tests') {
                    steps {
                        echo 'Running unit tests...'
                    }
                }
                stage('Integration Tests') {
                    steps {
                        echo 'Running integration tests...'
                    }
                }
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying...'
            }
        }
    }
}
  1. 指定 Agent agent

可以在 stage 中单独指定 agent,覆盖全局的 agent 设置。

groovy
pipeline {
    agent none  // 全局不指定 agent
    stages {
        stage('Build') {
            agent { label 'linux' }  // 该阶段使用 linux 节点
            steps {
                echo 'Building on Linux...'
            }
        }
        stage('Test') {
            agent { label 'windows' }  // 该阶段使用 windows 节点
            steps {
                echo 'Testing on Windows...'
            }
        }
    }
}
  1. 标记 stage 状态 post

可以在阶段执行完成后,通过 post 块来执行不同的操作(例如:清理工作、发送通知等)。

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
            post {
                always {
                    echo 'This always runs after the Build stage.'
                }
                success {
                    echo 'Build succeeded!'
                }
                failure {
                    echo 'Build failed.'
                }
            }
        }
    }
}
  • always:无论 stage 成功还是失败都会执行。
  • success:仅在 stage 成功时执行。
  • failure:仅在 stage 失败时执行。

stage 的更多控制选项

  • input:可以要求用户在流水线中进行人工确认。

    groovy
    stage('Deploy') {
        input {
            message 'Do you want to deploy to production?'
            ok 'Deploy!'
        }
        steps {
            echo 'Deploying...'
        }
    }
  • failFast:在并行阶段中,可以指定如果其中一个阶段失败,其他阶段立即停止执行。

    groovy
    parallel {
        stage('Unit Tests') {
            steps {
                echo 'Running unit tests...'
            }
        }
        stage('Integration Tests') {
            failFast true
            steps {
                echo 'Running integration tests...'
            }
        }
    }

tools

tools 指令用于定义流水线中需要使用的工具。它允许你指定 Jenkins 中预配置的工具(如 JDK、Maven、Gradle 等)以供某个 stage 或整个流水线使用。使用 tools 指令可以确保 Jenkins 在执行构建时使用正确的工具版本。

基本语法

groovy
pipeline {
    agent any
    tools {
        // 指定所需的工具
        jdk 'JDK 11'
        maven 'Maven 3.6.3'
    }
    stages {
        stage('Build') {
            steps {
                sh 'mvn clean install'
            }
        }
    }
}

关键点

  • tools 指令可以在全局范围内(如 pipeline 级别)指定,也可以在单独的 stage 级别指定。
  • 你需要确保这些工具已经在 Jenkins 的全局工具配置中预先配置好。

tools 可支持的工具类型

  • jdk: Java Development Kit (JDK) 的版本。
  • maven: Apache Maven 版本。
  • gradle: Gradle 构建工具的版本。
  • ant: Apache Ant 的版本。
  • nodejs: Node.js 版本(需要安装 NodeJS 插件)。
  • go: Go 编译器的版本(需要安装 Go 插件)。
  • python: Python 版本(需要安装 Python 插件)。

示例

  1. 全局定义工具

在整个流水线中使用同一个工具版本:

groovy
pipeline {
    agent any
    tools {
        jdk 'JDK 11'
        maven 'Maven 3.8.1'
    }
    stages {
        stage('Build') {
            steps {
                sh 'mvn clean install'
            }
        }
    }
}
  • jdk 'JDK 11' 表示使用预先在 Jenkins 中配置的名为 JDK 11 的 JDK。
  • maven 'Maven 3.8.1' 表示使用 Maven 3.8.1。
  1. 在单个 stage 中指定工具

你可以为某个特定阶段指定工具,而不是在整个流水线中使用相同的工具。

groovy
pipeline {
    agent any
    stages {
        stage('Build with JDK 8') {
            tools {
                jdk 'JDK 8'
                maven 'Maven 3.5.4'
            }
            steps {
                sh 'mvn clean install'
            }
        }
        stage('Test with JDK 11') {
            tools {
                jdk 'JDK 11'
            }
            steps {
                sh 'mvn test'
            }
        }
    }
}
  • Build with JDK 8 阶段使用 JDK 8 和 Maven 3.5.4。
  • Test with JDK 11 阶段使用 JDK 11。
  1. 使用多种工具
groovy
pipeline {
    agent any
    tools {
        jdk 'JDK 11'
        maven 'Maven 3.6.3'
        gradle 'Gradle 6.5'
    }
    stages {
        stage('Build Maven') {
            steps {
                sh 'mvn clean install'
            }
        }
        stage('Build Gradle') {
            steps {
                sh './gradlew build'
            }
        }
    }
}
  • 上面的例子在整个流水线中定义了多个工具(JDK 11、Maven、Gradle),并在不同的阶段中使用不同的构建工具。

预配置工具

在 Jenkins 管理界面中,你可以通过以下步骤配置这些工具:

  1. 进入 Jenkins 的 "Manage Jenkins" → "Global Tool Configuration"。
  2. 在页面中找到对应的工具配置部分(如 JDK、Maven、Gradle 等)。
  3. 配置相应的工具名称和版本。

确保在流水线脚本中指定的工具名称与 Jenkins 中预配置的名称一致。

工具路径管理

tools 指令会将所指定的工具自动加入到 PATH 中,使得在流水线的步骤中可以直接调用工具命令,而不需要手动指定路径。

input

input 指令用于在流水线执行过程中暂停,等待用户输入或手动确认。这个指令通常用于手动批准某些操作(例如部署到生产环境),让用户在流水线某个阶段中进行干预。

基本语法

groovy
pipeline {
    agent any
    stages {
        stage('Deploy') {
            steps {
                input {
                    message "Do you want to deploy to production?"
                    ok "Deploy!"
                }
                echo 'Deploying...'
            }
        }
    }
}

关键点

  • message: 用户看到的提示信息,说明需要他们做什么决定。
  • ok: 提交按钮上的文本,当用户点击按钮后,流水线将继续执行。
  • input 会使流水线暂停,直到某个 Jenkins 用户输入并确认后,才会继续执行。

input 进阶用法

  1. 指定用户权限

你可以指定允许批准的用户。

groovy
pipeline {
    agent any
    stages {
        stage('Deploy') {
            steps {
                input {
                    message "Deploy to production?"
                    ok "Yes, let's deploy!"
                    submitter "admin,user1"  // 只有 admin 和 user1 可以批准
                }
                echo 'Deploying...'
            }
        }
    }
}
  1. 带参数的 input

可以让用户在继续之前输入一些参数。这个功能非常有用,特别是在动态部署等场景中,用户可以选择某个选项或输入值。

groovy
pipeline {
    agent any
    stages {
        stage('User Input') {
            steps {
                script {
                    def userInput = input(
                        id: 'userInput', message: 'Please select deployment option:',
                        parameters: [
                            string(name: 'Target', defaultValue: 'staging', description: 'Where to deploy'),
                            booleanParam(name: 'Approval', defaultValue: false, description: 'Approve deployment')
                        ]
                    )
                    echo "Deploying to ${userInput.Target}"
                }
            }
        }
    }
}
  • parameters: 允许用户输入的参数,可以是 stringbooleanchoice 等类型。
  • id: 可选的唯一标识符,便于在其他地方引用此输入步骤。
  1. 超时设置 timeout

可以为 input 步骤设置一个超时时间,防止流水线无限期地等待用户输入。

groovy
pipeline {
    agent any
    stages {
        stage('Deploy') {
            steps {
                script {
                    try {
                        timeout(time: 10, unit: 'MINUTES') {
                            input {
                                message "Deploy to production?"
                                ok "Deploy!"
                            }
                        }
                    } catch (err) {
                        echo "User did not approve deployment within 10 minutes."
                        currentBuild.result = 'ABORTED'
                    }
                }
            }
        }
    }
}
  • timeout: 如果用户没有在规定时间内提供输入,流水线会继续执行,并且可以捕获该超时异常。
  1. 条件控制与分支逻辑

可以根据用户的输入执行不同的操作。

groovy
pipeline {
    agent any
    stages {
        stage('Deploy') {
            steps {
                script {
                    def userInput = input(
                        message: 'Choose deployment environment:',
                        parameters: [choice(name: 'Environment', choices: ['staging', 'production'], description: 'Select the environment')]
                    )
                    if (userInput == 'production') {
                        echo 'Deploying to production...'
                    } else {
                        echo 'Deploying to staging...'
                    }
                }
            }
        }
    }
}
  1. 设置 input 条件

可以通过 when 条件判断是否执行 input 步骤。

groovy
pipeline {
    agent any
    stages {
        stage('Deploy') {
            when {
                branch 'main'  // 仅当分支是 'main' 时才执行 input 步骤
            }
            steps {
                input {
                    message "Do you want to deploy to production?"
                    ok "Deploy!"
                }
                echo 'Deploying...'
            }
        }
    }
}
  1. 捕获 input 拒绝操作

当用户拒绝操作时,可以捕获错误并处理。

groovy
pipeline {
    agent any
    stages {
        stage('Deploy') {
            steps {
                script {
                    try {
                        input {
                            message "Do you want to deploy to production?"
                            ok "Deploy!"
                        }
                    } catch (err) {
                        echo "User aborted deployment!"
                        currentBuild.result = 'ABORTED'
                    }
                }
            }
        }
    }
}

when

when 指令用于控制某个阶段 (stage) 是否执行。它通过条件判断来动态决定是否执行流水线的某些部分。你可以基于分支、环境变量、标记、文件变化等多种条件进行控制。

基本语法

groovy
pipeline {
    agent any
    stages {
        stage('Test') {
            when {
                branch 'main'
            }
            steps {
                echo 'Running tests on the main branch'
            }
        }
    }
}

关键点

  • when 指令放在 stage 中,用于判断是否执行该 stage
  • 可以通过多种条件来决定阶段的执行,也可以组合多个条件。

常用的 when 条件

  1. branch

判断当前分支名是否满足条件。

groovy
pipeline {
    agent any
    stages {
        stage('Deploy') {
            when {
                branch 'main'
            }
            steps {
                echo 'Deploying on main branch'
            }
        }
    }
}
  • branch:只在指定的分支上执行。例如:branch 'main' 表示只在 main 分支执行该阶段。
  1. expression

使用 Groovy 表达式进行条件判断。

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            when {
                expression {
                    return env.BUILD_NUMBER == '5'
                }
            }
            steps {
                echo 'This is build number 5'
            }
        }
    }
}
  • expression:允许使用 Groovy 脚本进行复杂条件判断。可以返回 truefalse
  1. environment

根据环境变量的值来决定是否执行。

groovy
pipeline {
    agent any
    stages {
        stage('Deploy') {
            when {
                environment name: 'DEPLOY_ENV', value: 'production'
            }
            steps {
                echo 'Deploying to production'
            }
        }
    }
}
  • environment:根据指定的环境变量值判断是否执行 stage。例如:environment name: 'DEPLOY_ENV', value: 'production' 表示当 DEPLOY_ENV 环境变量的值为 production 时执行。
  1. equals

比较两个值是否相等,常用于环境变量比较。

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            when {
                equals expected: 'dev', actual: env.BRANCH_NAME
            }
            steps {
                echo 'Building on dev branch'
            }
        }
    }
}
  • equals:判断 expectedactual 值是否相等。
  1. not

条件取反。

groovy
pipeline {
    agent any
    stages {
        stage('Test') {
            when {
                not {
                    branch 'main'
                }
            }
            steps {
                echo 'Not on the main branch'
            }
        }
    }
}
  • not:将条件逻辑取反。上例中,只有当前分支不是 main 时,Test 阶段才会执行。
  1. changeset

判断工作区中是否有文件变化,常用于增量构建。

groovy
pipeline {
    agent any
    stages {
        stage('Test') {
            when {
                changeset "**/*.java"
            }
            steps {
                echo 'Java files have changed'
            }
        }
    }
}
  • changeset:判断某些文件是否发生了变化。支持通配符表达式,例如 **/*.java 表示 Java 文件发生了变化。
  1. changelog

判断是否有基于 SCM 的提交更改。

groovy
pipeline {
    agent any
    stages {
        stage('Test') {
            when {
                changelog ".*TEST.*"
            }
            steps {
                echo 'Commit contains TEST'
            }
        }
    }
}
  • changelog:如果提交日志包含特定的正则表达式,则执行该阶段。适合用于检测某些特定的提交信息。
  1. buildingTag

判断当前是否构建了一个标签(tag)。

groovy
pipeline {
    agent any
    stages {
        stage('Deploy') {
            when {
                buildingTag()
            }
            steps {
                echo 'Building a tag'
            }
        }
    }
}
  • buildingTag:如果是基于 SCM 的标签构建,则执行该阶段。
  1. beforeAgent

如果你想在 agent 分配之前执行 when 条件,可以使用 beforeAgent true

groovy
pipeline {
    agent any
    stages {
        stage('Test') {
            when {
                branch 'main'
                beforeAgent true
            }
            steps {
                echo 'Running tests on the main branch'
            }
        }
    }
}
  • beforeAgent:默认为 false,设置为 true 时,在 agent 分配前进行条件判断,可以节省不必要的资源分配。
  1. allOf 和 anyOf

用于组合多个条件,可以进行复杂的条件逻辑。

  • allOf:所有条件都为真时执行。
  • anyOf:只要有一个条件为真就执行。
groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            when {
                allOf {
                    branch 'main'
                    environment name: 'DEPLOY_ENV', value: 'production'
                }
            }
            steps {
                echo 'Building on main branch and production environment'
            }
        }
    }
}
groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            when {
                anyOf {
                    branch 'main'
                    branch 'develop'
                }
            }
            steps {
                echo 'Building on main or develop branch'
            }
        }
    }
}
编程洪同学服务平台是一个广泛收集编程相关内容和资源,旨在满足编程爱好者和专业开发人员的需求的网站。无论您是初学者还是经验丰富的开发者,都可以在这里找到有用的信息和资料,我们将助您提升编程技能和知识。
专业开发
高端定制
售后无忧
站内资源均为本站制作或收集于互联网等平台,如有侵权,请第一时间联系本站,敬请谅解!本站资源仅限于学习与参考,严禁用于各种非法活动,否则后果自行负责,本站概不承担!