跳到主要内容

常用插件详解

Jenkins 的强大之处在于其丰富的插件生态系统,超过 1800 个插件可以扩展 Jenkins 的功能。本章介绍最常用的插件及其配置和使用方法。

插件管理​

安装插件​

通过 Web 界面安装:

  1. 导航到 Manage Jenkins → Plugins → Available plugins
  2. 搜索需要的插件
  3. 勾选插件,点击 Install without restart 或 Download now and install after restart

通过 CLI 安装:

# 使用 Jenkins CLI
java -jar jenkins-cli.jar -s http://localhost:8080/ install-plugin PLUGIN_NAME

# 使用 REST API
curl -X POST -u user:token http://localhost:8080/pluginManager/installNecessaryPlugins -d '<install plugin="PLUGIN_ID@VERSION" />'

更新插件​

定期更新插件以获取新功能和安全修复:

  1. 导航到 Manage Jenkins → Plugins → Updates
  2. 选择要更新的插件
  3. 点击 Download now and install after restart

插件安全​

查看插件安全公告:Manage Jenkins → Plugins → Security warnings

建议:

  • 仅安装必需的插件
  • 定期审查已安装的插件
  • 关注安全公告,及时更新有漏洞的插件

源码管理插件​

Git Plugin​

Git Plugin 是 Jenkins 最基础的插件之一,提供 Git 版本控制系统的集成。

安装:Git Plugin

全局配置:

  1. 导航到 Manage Jenkins → Tools
  2. 配置 Git 可执行文件路径

Pipeline 中使用:

pipeline {
agent any

stages {
stage('Checkout') {
steps {
// 基本用法
git 'https://github.com/example/repo.git'

// 带凭据
git credentialsId: 'github-credentials',
url: 'https://github.com/example/repo.git'

// 指定分支
git branch: 'develop',
credentialsId: 'github-credentials',
url: 'https://github.com/example/repo.git'

// 使用 checkout scm(推荐用于多分支 Pipeline)
checkout scm
}
}
}
}

高级配置:

checkout([
$class: 'GitSCM',
branches: [[name: '*/main']],
extensions: [
// 清理工作空间
cleanBeforeCheckout(),
// 浅克隆
cloneOption(depth: 1, noTags: false, shallow: true),
// 子模块
submodule(recursiveSubmodules: true, reference: '')
],
userRemoteConfigs: [[
credentialsId: 'github-credentials',
url: 'https://github.com/example/repo.git'
]]
])

GitHub Branch Source Plugin​

用于 GitHub 仓库的多分支 Pipeline 和组织文件夹。

安装:GitHub Branch Source Plugin

配置 GitHub 服务器:

  1. 导航到 Manage Jenkins → System
  2. 找到 GitHub 部分
  3. 添加 GitHub 服务器配置:

创建 GitHub 凭据:

  1. 在 GitHub 创建 Personal Access Token(需要 repo 和 admin:repo_hook 权限)
  2. 在 Jenkins 中添加凭据:
    • 类型: Username with password
    • Username: GitHub 用户名
    • Password: Personal Access Token

多分支 Pipeline 配置:

创建 Multibranch Pipeline 时,选择 GitHub 作为 Branch Source:

Branch Sources:
- GitHub:
Credentials: github-token
Repository Owner: my-org
Repository: my-repo

Behaviors:
- Discover branches
- Discover pull requests from origin
- Filter by name:
Include: main develop feature/*

GitLab Plugin​

集成 GitLab 仓库和 Webhook。

安装:GitLab Plugin

配置 GitLab 连接:

  1. 导航到 Manage Jenkins → System
  2. 找到 GitLab 部分
  3. 配置连接:

Pipeline 中使用:

pipeline {
agent any

triggers {
gitlab(triggerOnPush: true, triggerOnMergeRequest: true)
}

stages {
stage('Build') {
steps {
checkout scm
sh 'mvn clean package'
}
}
}
}

代码质量插件​

SonarQube Scanner​

集成 SonarQube 代码质量分析平台。

安装:SonarQube Scanner for Jenkins

全局配置:

  1. 导航到 Manage Jenkins → System

  2. 找到 SonarQube servers 部分

  3. 添加服务器配置:

  4. 导航到 Manage Jenkins → Tools

  5. 配置 SonarQube Scanner 安装

创建 SonarQube 令牌:

  1. 登录 SonarQube
  2. 导航到 My Account → Security
  3. 生成令牌,复制到 Jenkins 凭据中

Pipeline 中使用:

pipeline {
agent any

stages {
stage('Build') {
steps {
sh 'mvn clean package'
}
}

stage('SonarQube Analysis') {
steps {
withSonarQubeEnv('SonarQube') {
sh 'mvn sonar:sonar'
}
}
}

stage('Quality Gate') {
steps {
timeout(time: 5, unit: 'MINUTES') {
waitForQualityGate abortPipeline: true
}
}
}
}
}

Maven 项目配置:

<!-- pom.xml -->
<properties>
<sonar.projectKey>my-project</sonar.projectKey>
<sonar.projectName>My Project</sonar.projectName>
<sonar.sources>src/main/java</sonar.sources>
<sonar.tests>src/test/java</sonar.tests>
</properties>

非 Maven 项目:

stage('SonarQube Analysis') {
steps {
withSonarQubeEnv('SonarQube') {
sh '''
sonar-scanner \
-Dsonar.projectKey=my-project \
-Dsonar.sources=src \
-Dsonar.tests=tests
'''
}
}
}

Warnings Next Generation​

收集和分析编译器警告。

安装:Warnings Next Generation Plugin

Pipeline 中使用:

pipeline {
agent any

stages {
stage('Build') {
steps {
sh 'mvn clean compile'
}
}

stage('Warnings') {
steps {
recordIssues(tools: [java(), javadoc(), mavenConsole()])
}
}
}
}

支持的解析器:

recordIssues(tools: [
java(), // Java 编译器
javadoc(), // Javadoc
mavenConsole(), // Maven 控制台
checkStyle(), // CheckStyle
pmdParser(), // PMD
spotBugs(), // SpotBugs
cppCheck(), // CppCheck
gcc() // GCC
])

通知插件​

Slack Notification​

发送构建通知到 Slack 频道。

安装:Slack Notification Plugin

创建 Slack App:

  1. 访问 https://api.slack.com/apps
  2. 创建新 App,选择 "Create new App" → "From scratch"
  3. 进入 OAuth & Permissions,添加以下 Bot Token Scopes:
    • chat:write
    • chat:write.customize
    • chat:write.public
  4. 安装 App 到工作区,获取 Bot User OAuth Token
  5. 邀请 Bot 到目标频道:/invite @YourBotName

Jenkins 全局配置:

  1. 导航到 Manage Jenkins → System
  2. 找到 Slack 部分
  3. 配置:
    • Workspace: your-workspace(不需要 .slack.com 后缀)
    • Credentials: 添加 Secret text 类型的凭据,值为 Bot User OAuth Token
    • Default channel: #builds
  4. 点击 Test Connection 验证

Pipeline 中使用:

pipeline {
agent any

post {
success {
slackSend(
color: 'good',
message: "构建成功: ${env.JOB_NAME} #${env.BUILD_NUMBER}\n详情: ${env.BUILD_URL}"
)
}
failure {
slackSend(
color: 'danger',
message: "构建失败: ${env.JOB_NAME} #${env.BUILD_NUMBER}\n详情: ${env.BUILD_URL}"
)
}
unstable {
slackSend(
color: 'warning',
message: "构建不稳定: ${env.JOB_NAME} #${env.BUILD_NUMBER}"
)
}
}
}

高级用法:

slackSend(
color: 'good',
message: 'Build passed!',
channel: '#deployments', // 覆盖默认频道
tokenCredentialId: 'slack-token', // 使用不同的凭据
baseUrl: 'https://your-company.slack.com/api/'
)

// 使用 blocks 和 attachments 构建富消息
slackSend(
blocks: [
[
type: 'section',
text: [
type: 'mrkdwn',
text: "*Build Status*\nJob: ${env.JOB_NAME}\nBuild: #${env.BUILD_NUMBER}"
]
]
]
)

Email Extension Plugin​

发送详细的构建邮件通知。

安装:Email Extension Plugin

全局配置:

  1. 导航到 Manage Jenkins → System
  2. 找到 Extended E-mail Notification 部分
  3. 配置 SMTP 服务器:
    • SMTP server: smtp.example.com
    • Default user E-mail suffix: @example.com
    • SMTP Authentication: 用户名和密码

Pipeline 中使用:

pipeline {
agent any

post {
always {
emailext(
subject: "Jenkins Build: ${env.JOB_NAME} #${env.BUILD_NUMBER} - ${currentBuild.currentResult}",
body: """
<h2>构建信息</h2>
<p><strong>项目:</strong> ${env.JOB_NAME}</p>
<p><strong>构建号:</strong> ${env.BUILD_NUMBER}</p>
<p><strong>状态:</strong> ${currentBuild.currentResult}</p>
<p><strong>触发者:</strong> ${env.BUILD_USER}</p>
<p><strong>详情:</strong> <a href="${env.BUILD_URL}">${env.BUILD_URL}</a></p>
""",
to: '[email protected]',
mimeType: 'text/html',
attachLog: true
)
}
}
}

按构建结果发送:

post {
success {
emailext(
subject: "✅ 构建成功: ${env.JOB_NAME}",
body: '构建成功,详情请查看构建日志。',
to: '[email protected]'
)
}
failure {
emailext(
subject: "❌ 构建失败: ${env.JOB_NAME}",
body: '构建失败,请检查控制台输出。',
to: '[email protected],[email protected]',
attachLog: true
)
}
}

钉钉通知​

使用钉钉机器人发送构建通知。

安装:DingTalk Plugin

创建钉钉机器人:

  1. 在钉钉群中添加自定义机器人
  2. 安全设置选择"自定义关键词",添加"构建"
  3. 获取 Webhook URL 和加签密钥

Jenkins 配置:

  1. 导航到 Manage Jenkins → System
  2. 找到 钉钉配置 部分
  3. 添加机器人配置

Pipeline 中使用:

pipeline {
agent any

post {
success {
dingtalk(
robot: 'dingtalk-robot',
type: 'MARKDOWN',
title: '构建成功',
text: [
"### 构建成功",
"- 项目: ${env.JOB_NAME}",
"- 构建: #${env.BUILD_NUMBER}",
"- [查看详情](${env.BUILD_URL})"
]
)
}
}
}

部署插件​

Kubernetes Plugin​

在 Kubernetes 集群中运行动态 Agent。

安装:Kubernetes Plugin

配置 Kubernetes 云:

  1. 导航到 Manage Jenkins → Nodes and Clouds → Configure Clouds
  2. 添加 Kubernetes 云:

Pipeline 中使用:

pipeline {
agent {
kubernetes {
yaml '''
apiVersion: v1
kind: Pod
spec:
containers:
- name: maven
image: maven:3.9-eclipse-temurin-21
command: ['cat']
tty: true
volumeMounts:
- name: m2-cache
mountPath: /root/.m2
volumes:
- name: m2-cache
persistentVolumeClaim:
claimName: maven-cache
'''
}
}

stages {
stage('Build') {
steps {
container('maven') {
sh 'mvn clean package'
}
}
}
}
}

多容器 Pod:

pipeline {
agent {
kubernetes {
yaml '''
apiVersion: v1
kind: Pod
spec:
containers:
- name: maven
image: maven:3.9-eclipse-temurin-21
command: ['cat']
tty: true
- name: docker
image: docker:24.0
command: ['cat']
tty: true
volumeMounts:
- name: docker-sock
mountPath: /var/run/docker.sock
- name: kubectl
image: bitnami/kubectl:latest
command: ['cat']
tty: true
volumes:
- name: docker-sock
hostPath:
path: /var/run/docker.sock
'''
}
}

stages {
stage('Build') {
steps {
container('maven') {
sh 'mvn clean package'
}
}
}
stage('Docker Build') {
steps {
container('docker') {
sh 'docker build -t myapp .'
}
}
}
stage('Deploy') {
steps {
container('kubectl') {
sh 'kubectl apply -f deployment.yaml'
}
}
}
}
}

Docker Plugin​

集成 Docker 容器作为构建环境。

安装:Docker Plugin

配置 Docker 云:

  1. 导航到 Manage Jenkins → Nodes and Clouds → Configure Clouds
  2. 添加 Docker 云:
    • Name: docker
    • Docker Host URI: unix:///var/run/docker.sock

Pipeline 中使用:

pipeline {
agent {
docker {
image 'maven:3.9-eclipse-temurin-21'
args '-v $HOME/.m2:/root/.m2'
}
}

stages {
stage('Build') {
steps {
sh 'mvn clean package'
}
}
}
}

SSH Plugin​

通过 SSH 执行远程命令和部署。

安装:SSH Plugin / Publish Over SSH

配置 SSH 服务器:

  1. 导航到 Manage Jenkins → System
  2. 找到 SSH Servers 部分
  3. 添加服务器配置:
    • Name: production-server
    • Hostname: server.example.com
    • Username: deploy
    • Remote Directory: /opt/deploy

Pipeline 中使用:

pipeline {
agent any

stages {
stage('Deploy') {
steps {
sshPublisher(
publishers: [
sshPublisherDesc(
configName: 'production-server',
transfers: [
sshTransfer(
sourceFiles: 'target/*.jar',
removePrefix: 'target',
remoteDirectory: 'app',
execCommand: 'systemctl restart myapp'
)
]
)
]
)
}
}
}
}

构建工具插件​

Maven Integration Plugin​

集成 Maven 构建工具。

安装:Maven Integration Plugin

全局工具配置:

  1. 导航到 Manage Jenkins → Tools
  2. 添加 Maven 安装:
    • Name: Maven-3.9
    • Install automatically: 勾选
    • Version: 选择版本

Pipeline 中使用:

pipeline {
agent any

tools {
maven 'Maven-3.9'
jdk 'JDK-21'
}

stages {
stage('Build') {
steps {
sh 'mvn clean package'
}
}
}
}

NodeJS Plugin​

集成 Node.js 环境。

安装:NodeJS Plugin

全局工具配置:

  1. 导航到 Manage Jenkins → Tools
  2. 添加 NodeJS 安装:
    • Name: NodeJS-20
    • Install automatically: 勾选
    • Version: 选择版本

Pipeline 中使用:

pipeline {
agent any

tools {
nodejs 'NodeJS-20'
}

stages {
stage('Install') {
steps {
sh 'npm ci'
}
}
stage('Build') {
steps {
sh 'npm run build'
}
}
stage('Test') {
steps {
sh 'npm test'
}
}
}
}

其他实用插件​

Build User Vars Plugin​

获取触发构建的用户信息。

安装:Build User Vars Plugin

使用:

pipeline {
agent any

stages {
stage('Info') {
steps {
wrap([$class: 'BuildUser']) {
echo "Build user: ${env.BUILD_USER}"
echo "Build user ID: ${env.BUILD_USER_ID}"
echo "Build user email: ${env.BUILD_USER_EMAIL}"
}
}
}
}
}

AnsiColor Plugin​

在控制台输出中显示彩色日志。

安装:AnsiColor Plugin

使用:

pipeline {
agent any

options {
ansiColor('xterm')
}

stages {
stage('Build') {
steps {
sh '''
echo '\033[32mGreen text\033[0m'
echo '\033[31mRed text\033[0m'
echo '\033[33mYellow text\033[0m'
'''
}
}
}
}

Timestamper Plugin​

为控制台日志添加时间戳。

安装:Timestamper Plugin

使用:

pipeline {
agent any

options {
timestamps()
}

stages {
stage('Build') {
steps {
echo 'This will have a timestamp'
}
}
}
}

Job DSL Plugin​

使用代码定义 Jenkins 任务。

安装:Job DSL Plugin

使用:

// 在 Seed Job 中定义其他任务
folder('my-folder')

multibranchPipelineJob('my-folder/my-project') {
branchSources {
github {
repositoryUrl('https://github.com/example/repo')
credentialsId('github-credentials')
}
}
}

pipelineJob('my-folder/deploy-job') {
definition {
cpsScm {
scm {
git {
remote {
url('https://github.com/example/repo')
credentials('github-credentials')
}
branch('main')
}
}
scriptPath('Jenkinsfile.deploy')
}
}
}

Configuration as Code (JCasC)​

使用 YAML 文件配置 Jenkins。

安装:Configuration as Code Plugin

配置文件示例:

# jenkins.yaml
jenkins:
systemMessage: "Welcome to Jenkins!"
numExecutors: 0

securityRealm:
local:
allowsSignup: false

authorizationStrategy:
globalMatrix:
permissions:
- "Overall/Read:anonymous"
- "Overall/Administer:admin"

clouds:
- kubernetes:
name: "kubernetes"
serverUrl: "https://kubernetes.default"
namespace: "jenkins"
jenkinsUrl: "http://jenkins:8080"

unclassified:
location:
url: "https://jenkins.example.com/"

插件推荐清单​

基础必备​

插件用途
GitGit 版本控制集成
PipelinePipeline 支持
Pipeline: Stage ViewPipeline 可视化
Credentials Binding凭据绑定
Timestamper日志时间戳
AnsiColor彩色日志

源码管理​

插件用途
GitHub Branch SourceGitHub 多分支
GitLabGitLab 集成
Bitbucket Branch SourceBitbucket 集成
Multibranch Scan Webhook TriggerWebhook 触发扫描

代码质量​

插件用途
SonarQube Scanner代码质量分析
Warnings Next Generation编译警告收集
Code Coverage API代码覆盖率

通知​

插件用途
Slack NotificationSlack 通知
Email Extension邮件通知
DingTalk钉钉通知

部署​

插件用途
KubernetesK8s 集成
Docker PipelineDocker 集成
SSHSSH 部署

管理​

插件用途
Configuration as Code配置即代码
Job DSL任务即代码
Audit Trail审计日志
Build User Vars构建用户信息

下一步​