跳到主要内容

Jenkins 速查表

快速查阅 Jenkins 常用命令、配置和语法。

常用 CLI 命令

服务管理

# 启动 Jenkins
sudo systemctl start jenkins

# 停止 Jenkins
sudo systemctl stop jenkins

# 重启 Jenkins
sudo systemctl restart jenkins

# 查看状态
sudo systemctl status jenkins

# 查看日志
sudo journalctl -u jenkins -f
sudo tail -f /var/log/jenkins/jenkins.log

Docker 命令

# 运行 Jenkins
docker run -d \
--name jenkins \
-p 8080:8080 \
-p 50000:50000 \
-v jenkins_home:/var/jenkins_home \
jenkins/jenkins:lts

# 查看日志
docker logs -f jenkins

# 获取初始密码
docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword

# 进入容器
docker exec -it jenkins bash

Pipeline 语法速查

基本结构

pipeline {
agent any

environment {
VAR = 'value'
}

stages {
stage('Build') {
steps {
echo 'Building...'
}
}
}

post {
always {
cleanWs()
}
}
}

Agent 配置

// 任意节点
agent any

// 指定标签
agent { label 'linux' }

// 指定节点
agent { node { label 'linux' } }

// Docker 容器
agent {
docker {
image 'node:16'
args '-v /tmp:/tmp'
}
}

// Kubernetes
agent {
kubernetes {
yaml '''...'''
}
}

// 无代理(阶段级指定)
agent none

参数类型

parameters {
// 字符串
string(name: 'NAME', defaultValue: 'value', description: '描述')

// 选项
choice(name: 'ENV', choices: ['dev', 'test', 'prod'], description: '环境')

// 布尔值
booleanParam(name: 'SKIP_TESTS', defaultValue: false, description: '跳过测试')

// 文本
text(name: 'DESC', defaultValue: '', description: '描述')

// 密码
password(name: 'SECRET', description: '密码')

// 文件
file(name: 'FILE', description: '文件')
}

When 条件

when {
branch 'main'
}

when {
environment name: 'ENV', value: 'prod'
}

when {
expression { params.DEPLOY == true }
}

when {
allOf {
branch 'main'
expression { params.RELEASE == true }
}
}

when {
anyOf {
branch 'main'
branch 'release/*'
}
}

when {
not {
branch 'develop'
}
}

并行执行

stage('Tests') {
parallel {
stage('Unit') {
steps {
sh 'npm run test:unit'
}
}
stage('Integration') {
steps {
sh 'npm run test:integration'
}
}
}
}

Post 条件

post {
always { }
success { }
failure { }
unstable { }
aborted { }
changed { }
fixed { }
regression { }
}

常用步骤

// Shell 命令
sh 'command'
sh '''
multi
line
'''

// Windows 批处理
bat 'command'

// PowerShell
powershell 'command'

// 输出
echo 'message'

// Git
git 'https://github.com/user/repo.git'
git branch: 'main', url: 'https://github.com/user/repo.git'

// 归档产物
archiveArtifacts artifacts: 'target/*.jar', fingerprint: true

// 发布 JUnit 报告
junit 'target/surefire-reports/*.xml'

// 清理工作空间
cleanWs()

// 输入
input message: 'Continue?'
input message: 'Choose:', parameters: [choice(name: 'ENV', choices: ['dev', 'prod'])]

// 超时
timeout(time: 30, unit: 'MINUTES') {
sh 'long-running-command'
}

// 重试
retry(3) {
sh 'flaky-command'
}

// 睡眠
sleep(time: 30, unit: 'SECONDS')

脚本块

script {
// 条件判断
if (env.BRANCH_NAME == 'main') {
echo 'Main branch'
}

// 循环
for (int i = 0; i < 10; i++) {
echo "Step ${i}"
}

// 异常处理
try {
sh 'risky-command'
} catch (Exception e) {
echo "Error: ${e.getMessage()}"
}

// 动态并行
def tests = [:]
for (int i = 0; i < 4; i++) {
def index = i
tests["Test ${i}"] = {
echo "Running test ${index}"
}
}
parallel tests
}

环境变量

内置变量

变量说明
BUILD_NUMBER构建编号
BUILD_ID构建 ID
BUILD_URL构建 URL
JOB_NAME任务名称
JOB_URL任务 URL
WORKSPACE工作空间路径
NODE_NAME节点名称
BUILD_USER触发用户
GIT_COMMITGit 提交 ID
GIT_BRANCHGit 分支
GIT_URLGit 仓库 URL

使用方式

// Pipeline 中
${env.BUILD_NUMBER}
${BUILD_NUMBER}

// Shell 中
${BUILD_NUMBER}
$BUILD_NUMBER

// Windows 中
%BUILD_NUMBER%

凭据使用

// 用户名密码
environment {
CREDS = credentials('credential-id')
}
// 使用: ${CREDS_USR} ${CREDS_PSW}

// SSH 密钥
sshagent(['ssh-credential-id']) {
sh 'git clone [email protected]:user/repo.git'
}

// Secret 文本
withCredentials([string(credentialsId: 'secret-id', variable: 'SECRET')]) {
sh 'echo $SECRET'
}

// 文件
withCredentials([file(credentialsId: 'file-id', variable: 'FILE')]) {
sh 'cat $FILE'
}

Docker 集成

// 构建镜像
docker.build("my-image:${env.BUILD_NUMBER}")

// 使用镜像运行
docker.image('node:16').inside {
sh 'npm install'
sh 'npm test'
}

// 推送到仓库
docker.withRegistry('https://registry.example.com', 'credentials-id') {
docker.image('my-image').push('latest')
}

常用插件

源码管理

  • Git Plugin - Git 集成
  • GitHub Branch Source - GitHub 多分支
  • Bitbucket Branch Source - Bitbucket 集成

构建工具

  • Maven Integration - Maven 构建
  • Gradle Plugin - Gradle 构建
  • NodeJS Plugin - Node.js 支持

部署

  • Publish Over SSH - SSH 部署
  • Deploy to container - 容器部署
  • Kubernetes CLI - K8s 部署

通知

  • Email Extension - 邮件通知
  • Slack Notification - Slack 通知
  • DingTalk Plugin - 钉钉通知

代码质量

  • SonarQube Scanner - 代码扫描
  • Warnings Next Generation - 编译警告
  • Code Coverage API - 覆盖率报告

定时表达式

Cron 语法

* * * * *
│ │ │ │ │
│ │ │ │ └── 星期 (0-7, 0和7都是周日)
│ │ │ └──── 月份 (1-12)
│ │ └────── 日期 (1-31)
│ └──────── 小时 (0-23)
└────────── 分钟 (0-59)

常用示例

// 每15分钟
H/15 * * * *

// 每小时
H * * * *

// 每2小时
H H/2 * * *

// 每天凌晨2点
H 2 * * *

// 工作日早上8点
H 8 * * 1-5

// 每周日凌晨
H H * * 0

配置文件路径

文件路径
主配置/var/lib/jenkins/config.xml
任务配置/var/lib/jenkins/jobs/[job-name]/config.xml
用户配置/var/lib/jenkins/users/[username]/config.xml
插件目录/var/lib/jenkins/plugins/
工作空间/var/lib/jenkins/workspace/
日志目录/var/lib/jenkins/logs/

故障排查

常见问题

# 端口被占用
sudo netstat -tulpn | grep 8080
sudo systemctl stop jenkins
sudo nano /etc/default/jenkins # 修改 HTTP_PORT

# 内存不足
sudo nano /etc/default/jenkins
# 修改: JAVA_OPTS="-Xmx2048m -Xms512m"

# 权限问题
sudo chown -R jenkins:jenkins /var/lib/jenkins
sudo usermod -aG docker jenkins

# 插件安装失败
# 1. 检查网络连接
# 2. 手动下载插件
# 3. 高级设置中上传插件

日志位置

# 系统日志
/var/log/jenkins/jenkins.log

# 系统服务日志
sudo journalctl -u jenkins

# Docker 日志
docker logs jenkins

REST API

常用端点

# 获取任务列表
curl -X GET http://jenkins/api/json

# 触发构建
curl -X POST http://jenkins/job/my-job/build

# 带参数构建
curl -X POST "http://jenkins/job/my-job/buildWithParameters?PARAM1=value1&PARAM2=value2"

# 获取构建信息
curl -X GET http://jenkins/job/my-job/lastBuild/api/json

# 获取控制台输出
curl -X GET http://jenkins/job/my-job/lastBuild/consoleText

# 创建任务
curl -X POST -H "Content-Type: application/xml" \
--data-binary @config.xml \
http://jenkins/createItem?name=my-job

最佳实践清单

安全

  • 启用安全矩阵授权
  • 使用凭据管理敏感信息
  • 定期更新 Jenkins 和插件
  • 配置 CSRF 保护
  • 使用 HTTPS

性能

  • Master 不执行构建
  • 合理配置执行器数量
  • 启用构建丢弃策略
  • 定期清理工作空间
  • 使用 Pipeline 代替 Freestyle

维护

  • 定期备份 JENKINS_HOME
  • 监控磁盘空间
  • 配置日志轮转
  • 文档化 Pipeline
  • 使用共享库复用代码