流水线基础 #

Jenkins Pipeline是Jenkins 2.x的核心特性,允许将整个CI/CD流程定义为代码,实现"Pipeline as Code"。

什么是Pipeline? #

Pipeline是一系列按顺序执行的阶段(Stage),每个阶段包含一个或多个步骤(Step),用于完成特定的构建、测试或部署任务。

text
┌─────────────────────────────────────────────────────────────┐
│                     Pipeline 流程                            │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  ┌─────────┐   ┌─────────┐   ┌─────────┐   ┌─────────┐    │
│  │ Checkout│──►│  Build  │──►│  Test   │──►│ Deploy  │    │
│  │         │   │         │   │         │   │         │    │
│  │ 检出代码│   │ 编译打包│   │ 运行测试│   │ 部署应用│    │
│  └─────────┘   └─────────┘   └─────────┘   └─────────┘    │
│       │             │             │             │          │
│       ▼             ▼             ▼             ▼          │
│    Step 1        Step 1        Step 1        Step 1       │
│    Step 2        Step 2        Step 2        Step 2       │
│                                                              │
└─────────────────────────────────────────────────────────────┘

Pipeline的优势 #

优势 说明
代码化 Pipeline定义在Jenkinsfile中,可版本管理
可视化 Stage View直观展示构建流程
可复用 支持共享库,代码复用
灵活性 支持复杂流程控制、条件判断、循环
可中断 支持暂停和恢复构建
并行执行 支持并行执行多个任务

Pipeline语法类型 #

Declarative Pipeline(声明式) #

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

Scripted Pipeline(脚本式) #

groovy
node {
    stage('Build') {
        echo 'Building...'
    }
    
    stage('Test') {
        echo 'Testing...'
    }
    
    stage('Deploy') {
        echo 'Deploying...'
    }
}

对比 #

特性 Declarative Scripted
语法 结构化、声明式 Groovy脚本
学习曲线
灵活性 中等
可读性 中等
错误检查 编译时 运行时
推荐程度 推荐 高级场景

Pipeline结构 #

基本结构 #

groovy
pipeline {
    agent any           // 指定执行代理
    
    environment {       // 环境变量
        APP_NAME = 'myapp'
    }
    
    stages {            // 阶段定义
        stage('Build') {
            steps {
                // 构建步骤
            }
        }
    }
    
    post {              // 构建后操作
        always {
            // 始终执行
        }
    }
}

完整结构 #

groovy
pipeline {
    agent any
    
    triggers {
        cron('H 2 * * *')
    }
    
    parameters {
        string(name: 'VERSION', defaultValue: '1.0.0')
    }
    
    environment {
        APP_NAME = 'myapp'
        VERSION = "${params.VERSION}"
    }
    
    options {
        timeout(time: 30, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '10'))
    }
    
    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }
        
        stage('Build') {
            steps {
                sh 'mvn clean package'
            }
        }
        
        stage('Test') {
            steps {
                sh 'mvn test'
            }
        }
        
        stage('Deploy') {
            when {
                branch 'main'
            }
            steps {
                sh 'kubectl apply -f k8s/'
            }
        }
    }
    
    post {
        always {
            junit '**/target/surefire-reports/*.xml'
        }
        success {
            echo '构建成功!'
        }
        failure {
            echo '构建失败!'
        }
        cleanup {
            cleanWs()
        }
    }
}

Agent配置 #

agent any #

在任意可用代理上执行:

groovy
pipeline {
    agent any
}

agent none #

在各个stage中单独指定代理:

groovy
pipeline {
    agent none
    
    stages {
        stage('Build') {
            agent { label 'linux' }
            steps { echo 'Building on Linux' }
        }
        
        stage('Test') {
            agent { label 'windows' }
            steps { echo 'Testing on Windows' }
        }
    }
}

agent label #

指定标签的代理:

groovy
pipeline {
    agent { label 'docker' }
}

agent docker #

使用Docker容器:

groovy
pipeline {
    agent {
        docker {
            image 'maven:3.8-openjdk-11'
            args '-v $HOME/.m2:/root/.m2'
        }
    }
    
    stages {
        stage('Build') {
            steps {
                sh 'mvn clean package'
            }
        }
    }
}

agent kubernetes #

使用Kubernetes Pod:

groovy
pipeline {
    agent {
        kubernetes {
            yaml '''
                apiVersion: v1
                kind: Pod
                spec:
                  containers:
                  - name: maven
                    image: maven:3.8-openjdk-11
                    command:
                    - cat
                    tty: true
            '''
        }
    }
}

Stages和Steps #

单个Stage #

groovy
stages {
    stage('Build') {
        steps {
            echo 'Building...'
            sh 'mvn clean package'
        }
    }
}

并行Stage #

groovy
stages {
    stage('Test') {
        parallel {
            stage('Unit Tests') {
                steps {
                    sh 'mvn test'
                }
            }
            stage('Integration Tests') {
                steps {
                    sh 'mvn verify -P integration'
                }
            }
        }
    }
}

嵌套Stage #

groovy
stages {
    stage('CI') {
        stages {
            stage('Build') {
                steps { echo 'Building...' }
            }
            stage('Test') {
                steps { echo 'Testing...' }
            }
        }
    }
}

Environment环境变量 #

全局环境变量 #

groovy
pipeline {
    agent any
    
    environment {
        APP_NAME = 'myapp'
        VERSION = "${BUILD_NUMBER}"
        JAVA_HOME = '/usr/lib/jvm/java-11'
    }
}

Stage级环境变量 #

groovy
stages {
    stage('Build') {
        environment {
            BUILD_ENV = 'production'
        }
        steps {
            echo "Building in ${BUILD_ENV}"
        }
    }
}

使用凭据 #

groovy
environment {
    DB_PASSWORD = credentials('db-password')
    AWS_ACCESS_KEY = credentials('aws-access-key')
}

Options选项 #

超时设置 #

groovy
options {
    timeout(time: 30, unit: 'MINUTES')
}

重试设置 #

groovy
options {
    retry(3)
}

丢弃旧构建 #

groovy
options {
    buildDiscarder(logRotator(numToKeepStr: '10'))
}

禁止并发 #

groovy
options {
    disableConcurrentBuilds()
}

跳过默认检出 #

groovy
options {
    skipDefaultCheckout()
}

时间戳 #

groovy
options {
    timestamps()
}

组合使用 #

groovy
options {
    timeout(time: 30, unit: 'MINUTES')
    retry(3)
    buildDiscarder(logRotator(numToKeepStr: '10'))
    timestamps()
    disableConcurrentBuilds()
}

When条件 #

分支条件 #

groovy
stage('Deploy') {
    when {
        branch 'main'
    }
    steps {
        sh 'kubectl apply -f k8s/'
    }
}

环境变量条件 #

groovy
stage('Deploy') {
    when {
        environment name: 'ENVIRONMENT', value: 'prod'
    }
    steps {
        sh 'deploy-to-prod.sh'
    }
}

表达式条件 #

groovy
stage('Deploy') {
    when {
        expression {
            return params.DEPLOY == true && params.ENVIRONMENT == 'prod'
        }
    }
    steps {
        sh 'deploy.sh'
    }
}

组合条件 #

groovy
stage('Deploy') {
    when {
        allOf {
            branch 'main'
            environment name: 'ENVIRONMENT', value: 'prod'
        }
    }
    steps {
        sh 'deploy.sh'
    }
}

stage('Test') {
    when {
        anyOf {
            branch 'main'
            branch 'develop'
        }
    }
    steps {
        sh 'test.sh'
    }
}

beforeAgent #

groovy
stage('Deploy') {
    when {
        beforeAgent true
        branch 'main'
    }
    agent { label 'production' }
    steps {
        sh 'deploy.sh'
    }
}

Post构建后操作 #

groovy
post {
    always {
        // 始终执行
        junit '**/target/surefire-reports/*.xml'
    }
    
    success {
        // 构建成功时执行
        echo '构建成功!'
        mail to: 'team@example.com',
             subject: "构建成功: ${JOB_NAME} #${BUILD_NUMBER}",
             body: '构建成功完成'
    }
    
    failure {
        // 构建失败时执行
        echo '构建失败!'
        mail to: 'team@example.com',
             subject: "构建失败: ${JOB_NAME} #${BUILD_NUMBER}",
             body: '构建失败,请检查'
    }
    
    unstable {
        // 构建不稳定时执行
        echo '构建不稳定!'
    }
    
    aborted {
        // 构建被中止时执行
        echo '构建被中止!'
    }
    
    cleanup {
        // 清理操作
        cleanWs()
    }
}

Jenkinsfile存放位置 #

仓库根目录 #

text
project/
├── Jenkinsfile
├── src/
├── pom.xml
└── README.md

自定义路径 #

在Pipeline配置中指定:

text
Script Path: ci/Jenkinsfile

多Jenkinsfile #

text
project/
├── Jenkinsfile          # 主流水线
├── Jenkinsfile.release  # 发布流水线
├── Jenkinsfile.nightly  # 夜间构建
└── src/

Pipeline语法生成器 #

Jenkins提供语法生成器帮助编写Pipeline:

  1. 进入任务配置页面
  2. 点击 Pipeline Syntax
  3. 选择步骤类型
  4. 填写参数
  5. 生成Pipeline代码

下一步学习 #

小结 #

  • Pipeline是Jenkins 2.x的核心特性
  • 支持Declarative和Scripted两种语法
  • 推荐使用Declarative语法
  • Pipeline定义在Jenkinsfile中
  • 支持丰富的条件和选项配置
  • post块处理构建后操作
最后更新:2026-03-28