jenkins详细的配置pipeline的代码

我将详细介绍 Jenkins 中源码管理、构建触发器、构建环境和构建步骤的各个要点。

Jenkins 构建配置详解

1. 源码管理 (Source Code Management)

1.1 Git

pipeline {
    agent any
    
    stages {
        stage('Checkout') {
            steps {
                git branch: 'main',
                    url: 'https://github.com/user/repo.git',
                    credentialsId: 'git-credentials'
            }
        }
    }
}

关键配置项

  1. Repository URL

    • HTTPS URL
    • SSH URL
    • 本地路径
  2. Credentials

    • Username/Password
    • SSH Key
    • Personal Access Token
  3. 分支配置

    // 指定分支
    branches: [[name: '*/main']]
    
    // 多分支配置
    branches: [
        [name: '*/main'],
        [name: '*/develop'],
        [name: 'refs/tags/*']
    ]
    
  4. 子模块选项

    extensions: [
        [$class: 'SubmoduleOption',
         disableSubmodules: false,
         recursiveSubmodules: true,
         trackingSubmodules: false]
    ]
    
  5. 稀疏检出

    extensions: [
        [$class: 'SparseCheckoutPaths', 
         sparseCheckoutPaths: [[path: 'path/to/include']]]
    ]
    

1.2 SVN

pipeline {
    agent any
    
    stages {
        stage('Checkout') {
            steps {
                checkout([$class: 'SubversionSCM',
                    locations: [[
                        credentialsId: 'svn-credentials',
                        local: '.',
                        remote: 'https://svn.example.com/repo'
                    ]],
                    workspaceUpdater: [$class: 'UpdateUpdater']])
            }
        }
    }
}

关键配置项

  1. Repository URL
  2. Credentials
  3. 检出策略
    • 更新
    • 清理后检出
    • 使用版本号

2. 构建触发器 (Build Triggers)

2.1 定时构建

pipeline {
    agent any
    
    triggers {
        // 每天凌晨2点构建
        cron('0 2 * * *')
        
        // 每周一到周五的工作时间内每4小时构建一次
        cron('0 9-17/4 * * 1-5')
    }
}

2.2 轮询 SCM

pipeline {
    agent any
    
    triggers {
        // 每5分钟检查一次代码变更
        pollSCM('*/5 * * * *')
    }
}

2.3 Webhook 触发

properties([
    pipelineTriggers([
        [
            $class: 'GenericTrigger',
            genericVariables: [
                [key: 'ref', value: '$.ref']
            ],
            causeString: 'Triggered by webhook',
            token: 'your-token'
        ]
    ])
])

2.4 上游项目触发

pipeline {
    agent any
    
    triggers {
        upstream(upstreamProjects: 'job1,job2', 
                threshold: hudson.model.Result.SUCCESS)
    }
}

3. 构建环境 (Build Environment)

3.1 环境变量

pipeline {
    agent any
    
    environment {
        JAVA_HOME = '/usr/lib/jvm/java-11'
        PATH = "${JAVA_HOME}/bin:${PATH}"
        MAVEN_OPTS = '-Xmx2048m'
    }
}

3.2 凭证管理

pipeline {
    agent any
    
    environment {
        DOCKER_CREDENTIALS = credentials('docker-hub')
        GIT_CREDENTIALS = credentials('git-credentials')
    }
    
    stages {
        stage('Build') {
            steps {
                withCredentials([
                    usernamePassword(credentialsId: 'my-credentials',
                                   usernameVariable: 'USER',
                                   passwordVariable: 'PASS')
                ]) {
                    sh 'docker login -u $USER -p $PASS'
                }
            }
        }
    }
}

3.3 工具配置

pipeline {
    agent any
    
    tools {
        maven 'Maven 3.8.4'
        jdk 'JDK 11'
        nodejs 'Node 14'
    }
}

3.4 构建包装器

pipeline {
    agent any
    
    options {
        timeout(time: 1, unit: 'HOURS')
        timestamps()
        ansiColor('xterm')
    }
}

4. 构建步骤 (Build Steps)

4.1 Shell 命令

pipeline {
    agent any
    
    stages {
        stage('Build') {
            steps {
                sh '''
                    mvn clean install
                    ./gradlew build
                    npm install
                    npm run build
                '''
            }
        }
    }
}

4.2 Windows 批处理

pipeline {
    agent any
    
    stages {
        stage('Build') {
            steps {
                bat '''
                    call mvn clean install
                    gradlew.bat build
                    npm install
                    npm run build
                '''
            }
        }
    }
}

4.3 Maven 构建

pipeline {
    agent any
    
    stages {
        stage('Build') {
            steps {
                withMaven(maven: 'Maven 3.8.4') {
                    sh 'mvn clean package'
                }
            }
        }
    }
}

4.4 Gradle 构建

pipeline {
    agent any
    
    stages {
        stage('Build') {
            steps {
                gradle 'clean build'
            }
        }
    }
}

4.5 Docker 构建

pipeline {
    agent any
    
    stages {
        stage('Build Docker Image') {
            steps {
                script {
                    docker.build("myapp:${BUILD_NUMBER}")
                }
            }
        }
        
        stage('Push Docker Image') {
            steps {
                script {
                    docker.withRegistry('https://registry.example.com', 'docker-credentials') {
                        docker.image("myapp:${BUILD_NUMBER}").push()
                    }
                }
            }
        }
    }
}

4.6 并行构建

pipeline {
    agent any
    
    stages {
        stage('Parallel Build') {
            parallel {
                stage('Build Frontend') {
                    steps {
                        sh 'npm run build'
                    }
                }
                stage('Build Backend') {
                    steps {
                        sh 'mvn clean install'
                    }
                }
            }
        }
    }
}

4.7 条件构建

pipeline {
    agent any
    
    stages {
        stage('Conditional Build') {
            when {
                branch 'main'
                environment name: 'DEPLOY_TO', value: 'production'
            }
            steps {
                sh './deploy.sh'
            }
        }
    }
}

4.8 构建后操作

pipeline {
    agent any
    
    stages {
        stage('Build') {
            steps {
                sh 'mvn clean package'
            }
        }
    }
    
    post {
        always {
            junit '**/target/surefire-reports/*.xml'
            archiveArtifacts artifacts: 'target/*.jar', fingerprint: true
        }
        success {
            mail to: 'team@example.com',
                 subject: "Pipeline '${currentBuild.fullDisplayName}' succeeded",
                 body: "Build succeeded. Check console output at ${BUILD_URL}"
        }
        failure {
            mail to: 'team@example.com',
                 subject: "Pipeline '${currentBuild.fullDisplayName}' failed",
                 body: "Build failed. Check console output at ${BUILD_URL}"
        }
    }
}

5. 最佳实践建议

  1. 源码管理

    • 使用凭证管理敏感信息
    • 配置适当的分支策略
    • 定期清理工作空间
  2. 构建触发器

    • 避免过于频繁的轮询
    • 优先使用 Webhook
    • 合理设置构建时间窗口
  3. 构建环境

    • 统一管理环境变量
    • 使用工具版本管理
    • 注意凭证的安全性
  4. 构建步骤

    • 模块化构建步骤
    • 使用并行构建提高效率
    • 添加适当的错误处理
    • 保存重要的构建产物

6. 性能优化建议

  1. 工作空间管理

    options {
        skipDefaultCheckout()
        disableConcurrentBuilds()
    }
    
  2. 构建缓存

    pipeline {
        agent any
        
        options {
            preserveStashes()
            buildDiscarder(logRotator(numToKeepStr: '10'))
        }
    }
    
  3. 资源限制

    pipeline {
        agent {
            docker {
                image 'maven:3.8.4-jdk-11'
                args '-v $HOME/.m2:/root/.m2 -m 4G'
            }
        }
    }
    

这些配置和建议应该能够帮助你更好地理解和使用 Jenkins 的各个构建组件。根据具体项目需求,可以选择性地使用这些功能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值