任务配置 #

本节将详细介绍Jenkins任务的各种配置选项,帮助你更好地定制构建流程。

配置区域概览 #

text
┌─────────────────────────────────────────────────────────────┐
│                    任务配置页面                              │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  1. General (通用配置)                                       │
│     - 描述、丢弃策略、并发控制                               │
│                                                              │
│  2. Source Code Management (源码管理)                        │
│     - Git、SVN、Mercurial                                   │
│                                                              │
│  3. Build Triggers (构建触发器)                              │
│     - 定时、轮询、远程触发                                   │
│                                                              │
│  4. Build Environment (构建环境)                             │
│     - 环境变量、工具、证书                                   │
│                                                              │
│  5. Build Steps (构建步骤)                                   │
│     - Shell、Maven、Gradle、Ant                             │
│                                                              │
│  6. Post-build Actions (构建后操作)                          │
│     - 归档、通知、触发其他任务                               │
│                                                              │
└─────────────────────────────────────────────────────────────┘

General 配置 #

描述信息 #

text
Description:
┌─────────────────────────────────────────────────────────────┐
│ 项目名称: my-app                                            │
│ 构建类型: CI/CD                                             │
│ 负责人: dev-team@example.com                                │
│                                                              │
│ 构建流程:                                                   │
│ 1. 检出代码                                                 │
│ 2. 编译打包                                                 │
│ 3. 运行测试                                                 │
│ 4. 部署到测试环境                                           │
└─────────────────────────────────────────────────────────────┘

丢弃旧构建 #

text
☑ Discard old builds

Strategy: Log Rotation

Max # of builds to keep: 10
Max # of builds to keep with artifacts: 5

Days to keep builds: 30
Days to keep artifacts: 14

并发控制 #

text
☐ Execute concurrent builds if necessary

☑ Do not allow concurrent builds

参数化构建 #

text
☑ This project is parameterized

┌─────────────────────────────────────────────────────────────┐
│ Boolean Parameter                                            │
│ Name: DEPLOY                                                 │
│ Default Value: true                                          │
│ Description: 是否部署到测试环境                              │
├─────────────────────────────────────────────────────────────┤
│ Choice Parameter                                             │
│ Name: ENVIRONMENT                                            │
│ Choices:                                                     │
│   dev                                                        │
│   test                                                       │
│   staging                                                    │
│   prod                                                       │
│ Description: 部署环境                                        │
├─────────────────────────────────────────────────────────────┤
│ String Parameter                                             │
│ Name: VERSION                                                │
│ Default Value: 1.0.0                                         │
│ Description: 应用版本号                                      │
├─────────────────────────────────────────────────────────────┤
│ Password Parameter                                           │
│ Name: DB_PASSWORD                                            │
│ Default Value:                                               │
│ Description: 数据库密码                                      │
├─────────────────────────────────────────────────────────────┤
│ File Parameter                                               │
│ Name: CONFIG_FILE                                            │
│ Description: 配置文件                                        │
├─────────────────────────────────────────────────────────────┤
│ Run Parameter                                                │
│ Name: UPSTREAM_BUILD                                         │
│ Project Name: upstream-job                                   │
│ Description: 上游构建                                        │
└─────────────────────────────────────────────────────────────┘

源码管理配置 #

Git详细配置 #

text
☑ Git

Repository URL: https://github.com/user/repo.git
Credentials: github-credentials
Branch Specifier: */main

┌─────────────────────────────────────────────────────────────┐
│ Additional Behaviours                                        │
├─────────────────────────────────────────────────────────────┤
│ Checkout to specific local branch                           │
│   Local branch: main                                         │
├─────────────────────────────────────────────────────────────┤
│ Clean after checkout                                         │
├─────────────────────────────────────────────────────────────┤
│ Clean before checkout                                        │
├─────────────────────────────────────────────────────────────┤
│ Sparse Checkout paths                                        │
│   Path: src/main                                             │
├─────────────────────────────────────────────────────────────┤
│ Submodule options                                            │
│   ☑ Recursively update submodules                           │
│   ☑ Update submodules to current revision                   │
├─────────────────────────────────────────────────────────────┤
│ Git LFS pull after checkout                                  │
├─────────────────────────────────────────────────────────────┤
│ Advanced clone behaviours                                    │
│   ☑ Shallow clone (depth: 1)                                │
│   ☑ Honor refspec on initial clone                          │
└─────────────────────────────────────────────────────────────┘

多仓库配置 #

text
Repositories:

Repository 1:
  Name: app
  URL: https://github.com/org/app.git
  Branch: */main

Repository 2:
  Name: shared-lib
  URL: https://github.com/org/shared-lib.git
  Branch: */main

SVN配置 #

text
☑ Subversion

Repository URL: svn://svn.example.com/repo/trunk
Credentials: svn-credentials
Local module directory: .

Checkout Strategy:
  ○ Use 'svn update' as much as possible
  ● Always check out a fresh copy

Ignore externals: ☐

构建触发器配置 #

定时触发 #

text
☑ Build periodically

Schedule:
┌─────────────────────────────────────────────────────────────┐
│ H 2 * * *       每天凌晨2点                                  │
│ H/15 * * * *    每15分钟                                     │
│ H 9-17 * * 1-5  工作时间每小时                               │
│ H 0 1 1 *       每月1号午夜                                  │
└─────────────────────────────────────────────────────────────┘

轮询SCM #

text
☑ Poll SCM

Schedule: H/5 * * * *

Ignore post-commit hooks: ☐

远程触发 #

text
☑ Trigger builds remotely

Authentication Token: my-secret-token

触发方式:
curl -X POST http://JENKINS_URL/job/my-job/build?token=my-secret-token

带参数触发:
curl -X POST http://JENKINS_URL/job/my-job/buildWithParameters?token=my-secret-token&ENVIRONMENT=prod

上游任务触发 #

text
☑ Build after other projects are built

Projects to watch: upstream-job, another-job

Trigger only if build is:
  ○ stable
  ○ unstable or better
  ○ failed or better

GitHub Webhook触发 #

text
☑ GitHub hook trigger for GITScm polling

GitLab Webhook触发 #

text
☑ Build when a change is pushed to GitLab

Events:
  ☑ Push Events
  ☑ Merge Request Events
  ☐ Tag Push Events
  ☐ Note Events
  ☐ Pipeline Events
  
Secret token: gitlab-webhook-token

构建环境配置 #

环境变量注入 #

text
☑ Inject environment variables to the build process

Properties Content:
┌─────────────────────────────────────────────────────────────┐
│ APP_NAME=my-app                                             │
│ BUILD_ENV=production                                        │
│ JAVA_HOME=/usr/lib/jvm/java-11                              │
│ MAVEN_OPTS=-Xmx1024m                                        │
│ PATH+EXTRA=/usr/local/bin                                   │
└─────────────────────────────────────────────────────────────┘

Properties File Path: env.properties

工具配置 #

text
☑ JDK
  JDK: JDK 11

☑ Maven
  Maven: Maven 3.8
  
☑ Ant
  Ant: Apache Ant 1.10

证书注入 #

text
☑ Use secret text(s) or file(s)

Bindings:
┌─────────────────────────────────────────────────────────────┐
│ Secret text:                                                 │
│   Variable: DOCKER_PASSWORD                                  │
│   Credentials: docker-hub-credentials                        │
├─────────────────────────────────────────────────────────────┤
│ Secret file:                                                 │
│   Variable: KUBECONFIG_FILE                                  │
│   Credentials: kubeconfig-credentials                        │
├─────────────────────────────────────────────────────────────┤
│ Username and Password (separated):                          │
│   Username Variable: DB_USER                                 │
│   Password Variable: DB_PASSWORD                             │
│   Credentials: database-credentials                          │
└─────────────────────────────────────────────────────────────┘

超时设置 #

text
☑ Abort the build if it's stuck

Time-out strategy:
  ○ Absolute
    Timeout minutes: 30
    
  ○ Elastic
    Timeout minutes: 60
    Timeout percentage: 150
    
  ○ No Activity
    Timeout minutes: 10

工作空间清理 #

text
☑ Delete workspace before build starts

☑ Wipe out current work space

控制台输出 #

text
☑ Color ANSI Console Output
  ANSI color map: xterm

☑ Timestamps in Console Output

构建步骤配置 #

Shell脚本 #

bash
#!/bin/bash
set -e

echo "=== 构建信息 ==="
echo "任务: ${JOB_NAME}"
echo "构建: ${BUILD_NUMBER}"
echo "环境: ${ENVIRONMENT}"

echo "=== 执行构建 ==="
mvn clean package -DskipTests=${SKIP_TESTS}

echo "=== 运行测试 ==="
if [ "${SKIP_TESTS}" != "true" ]; then
    mvn test
fi

echo "=== 构建完成 ==="

Windows批处理 #

batch
@echo off
echo === 构建信息 ===
echo 任务: %JOB_NAME%
echo 构建: %BUILD_NUMBER%

echo === 执行构建 ===
call mvn clean package

echo === 构建完成 ===

Maven构建 #

text
Maven Version: Maven 3.8

Goals and options: clean package -DskipTests=false

POM: pom.xml

Properties:
  environment=${ENVIRONMENT}
  version=${VERSION}

JVM Options: -Xmx1024m -XX:MaxPermSize=256m

Gradle构建 #

text
Gradle Version: Gradle 7.x

Tasks: clean build

Switches: --info --stacktrace

Build File: build.gradle

Python脚本 #

python
#!/usr/bin/env python3
import os
import subprocess

print("=== Python构建脚本 ===")
print(f"工作目录: {os.getcwd()}")

subprocess.run(["pip", "install", "-r", "requirements.txt"])
subprocess.run(["python", "manage.py", "test"])
subprocess.run(["python", "manage.py", "collectstatic", "--noinput"])

构建后操作配置 #

归档产物 #

text
☑ Archive the artifacts

Files to archive: 
  target/*.jar
  target/*.war
  dist/*

Exclude files:
  target/*-sources.jar

Follow symlink: ☐

JUnit测试报告 #

text
☑ Publish JUnit test result report

Test report XMLs: 
  **/target/surefire-reports/*.xml
  **/target/failsafe-reports/*.xml

Health report amplification factor: 1.0

Retain long standard output/error: ☐

代码覆盖率报告 #

text
☑ Record JaCoCo coverage report

Path to exec files: **/jacoco.exec
Path to class directories: **/classes
Path to source directories: **/src/main/java

Health metrics:
  Method: 80%
  Line: 80%
  Branch: 70%

邮件通知 #

text
☑ E-mail Notification

Recipients: team@example.com, lead@example.com

☐ Send e-mail for every unstable build
☑ Send separate e-mails to individuals who broke the build

Slack通知 #

text
☑ Slack Notifications

Notify on:
  ☑ Build Started
  ☑ Build Success
  ☑ Build Failure
  ☑ Build Unstable
  
Channel: #builds

触发下游任务 #

text
☑ Build other projects

Projects to build: downstream-job

Trigger only if build is:
  ● stable
  ○ unstable or better
  ○ failed or better

Wait for completion: ☐

配置最佳实践 #

1. 使用有意义的命名 #

text
Good: my-app-ci-build, user-service-deploy
Bad: job1, test, build

2. 添加详细描述 #

text
Description:
项目: 用户服务
类型: CI/CD流水线
负责人: backend-team@example.com
文档: https://wiki.example.com/my-app

3. 设置合理的丢弃策略 #

text
☑ Discard old builds
  Max # of builds to keep: 20
  Max # of builds to keep with artifacts: 5

4. 使用参数化构建 #

text
☑ This project is parameterized
  - Choice: ENVIRONMENT (dev/test/prod)
  - Boolean: SKIP_TESTS
  - String: VERSION

5. 设置构建超时 #

text
☑ Abort the build if it's stuck
  Timeout: 30 minutes

6. 使用环境变量文件 #

text
☑ Inject environment variables
  Properties File Path: jenkins.env

配置文件示例 #

jenkins.env #

properties
APP_NAME=my-app
MAVEN_OPTS=-Xmx2048m -XX:+UseG1GC
DOCKER_REGISTRY=registry.example.com
KUBERNETES_NAMESPACE=default

构建脚本示例 #

bash
#!/bin/bash
set -e

echo "=========================================="
echo "构建信息"
echo "=========================================="
echo "任务名称: ${JOB_NAME}"
echo "构建编号: ${BUILD_NUMBER}"
echo "目标环境: ${ENVIRONMENT}"
echo "跳过测试: ${SKIP_TESTS}"
echo "=========================================="

echo ">>> 检出代码"
git log -1 --pretty=format:"%h - %an, %ar : %s"

echo ">>> 编译项目"
mvn clean compile

echo ">>> 运行测试"
if [ "${SKIP_TESTS}" != "true" ]; then
    mvn test
fi

echo ">>> 打包应用"
mvn package -DskipTests

echo ">>> 构建完成"
ls -la target/*.jar

下一步学习 #

小结 #

  • 通用配置控制基本行为
  • 源码管理支持多种VCS
  • 触发器决定何时构建
  • 构建环境准备执行环境
  • 构建步骤执行具体任务
  • 构建后操作处理结果
最后更新:2026-03-28