文章

Jenkins-流水线常用配置

1. 设置BuildName

1.1. Job构建环境选项

1
2
3
构建环境 --> Set Build Name --> Build Name --> Build Description
Build Name: 构建标号,设置的参数
#${BUILD_NUMBER}-[${method}]

1.2. Pipline

在 Jenkins Pipeline 中设置构建名称可以通过 currentBuild.displayName 属性实现。你可以在任何阶段的脚本步骤中设置这个属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
pipeline {
    agent any
    
    stages {
        stage("Show Params"){
            steps {
                script {
                    currentBuild.displayName = "$BUILD_NUMBER $serviceName on $branch"
                    currentBuild.description = "$releaseVersion"
                }
            }
        }
    }
}

2. 设置环境变量

引用参数; Jenkins 系统变量: //凭据 –> 系统 –> 全局凭据

1
2
3
4
5
6
7
8
9
10
11
pipeline {
    agent any
    
    environment {
        actionLogId = "$params.actionLogId"
        branch = "$params.branch"
        serviceName = "$params.serviceName"
        releaseVersion = "$params.releaseVersion"
        HTTP_BLUEKING_TOKEN=credentials('CMDB_TOKEN') 
    }
}

3. 构建日志中添加时间戳

时间戳格式: HH:mm:ss.SSS, 固定无法修改

1
2
3
4
5
6
7
pipeline {
    agent any
    
    options {
        timestamps()
    }
}

4. 调用其他的Job

使用方式,解释:

  1. 通过 build 步骤触发名为 OtherJob 的 Job,并且等待它执行完成:
    1
    
    build job: 'OtherJob', wait: true
    
  2. 使用 rawBuild.getLog() 方法获取该 Job 最新的 50 行日志:
    1
    
    downstreamJob.rawBuild.getLog(50)
    
  3. 将获取到的日志输出到当前的 Job 控制台:
    1
    
    echo consoleOutput.join("\n")
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
pipeline {
   agent any

   stages {
       stage('Trigger Another Job') {
           steps {
               script {
                   // 调用其他 Job
                   def downstreamJob = build job: 'OtherJob', wait: true

                   // 获取该 Job 的日志
                   def consoleOutput = downstreamJob.rawBuild.getLog(50) // 获取最新的 50 行日志
                   echo "Logs from OtherJob:"
                   echo consoleOutput.join("\n")  // 打印日志
               }
           }
       }
   }
}

======================================================================

特殊使用:

  1. 异步调用:
    1
    
    build job: 'OtherJob', wait: false
    
  2. 获取所有日志:

    a.使用 getLog() 方法不传参数;

    b.使用 getLogText() 结合 readAll() 读取完整日志;

    1
    2
    3
    
    def consoleOutput = downstreamJob.rawBuild.getLogText().readAll()
    echo "Complete logs from OtherJob:"
    echo consoleOutput
    
  3. 获取子任务的结果和状态
    1
    2
    3
    4
    5
    
    if (downstreamJob.result == 'SUCCESS') {
    	echo "OtherJob completed successfully!"
    } else {
    	echo "OtherJob failed!"
    }
    
本文由作者按照 CC BY 4.0 进行授权