Jenkins pipeline使用篇
1.Pipeline定义CI/CD流水线
包含git 拉取代码 maven 编译打包,将打好的包推送到目标服务器,最后执行部署脚本
1.1 流水线整体示例
pipeline {
agent any // 指定在任意可用的 Jenkins 节点上运行
environment {
// 定义环境变量
MAVEN_HOME = tool 'Maven' // 假设已配置 Maven 工具
PATH = "${MAVEN_HOME}/bin:${env.PATH}"
DEPLOY_SERVER = 'your_deploy_server_ip' // 目标服务器 IP
DEPLOY_USER = 'your_deploy_user' // 目标服务器用户名
DEPLOY_PASSWORD = 'your_deploy_password' // 目标服务器密码
DEPLOY_SCRIPT = 'deploy.sh' // 部署脚本名称
ARTIFACT_NAME = 'your_artifact_name' // 打包后的文件名
}
stages {
stage('拉取代码') {
steps {
// 从 Git 仓库拉取代码
git branch: 'main', url: 'https://github.com/your-repo-url.git'
}
}
stage('编译打包') {
steps {
// 使用 Maven 编译打包
sh 'mvn clean package'
}
}
stage('推送包到目标服务器') {
steps {
// 使用 SCP 或其他方式将打包后的文件推送到目标服务器
sshPublisher(publishers: [
sshPublisherDesc(
configName: 'your_ssh_config_name', // 需要在 Jenkins 中配置 SSH 服务器
transfers: [
sshTransfer(
execCommand: "mkdir -p /path/to/deploy/${env.BUILD_NUMBER}", // 在目标服务器上创建目录
sourceFiles: "target/${env.ARTIFACT_NAME}", // 打包后的文件路径
removePrefix: 'target', // 移除本地路径前缀
remoteDirectory: "/path/to/deploy/${env.BUILD_NUMBER}" // 目标服务器上的目录
)
],
usePromotionTimestamp: false,
useWorkspaceInPromotion: false,
verbose: false
)
])
}
}
stage('执行部署脚本') {
steps {
script {
def remote = [name : env.HOST_NAME,
host : env.HOST,
user : env.HOST_USER,
identityFile : env.IDENTITY_FILE,
allowAnyHosts: true]
sshCommand remote: remote, command: "cd ${env.REMOTE_PATH_APP} && sh deploy.sh"
}
}
}
}
post {
success {
echo '部署成功!'
}
failure {
echo '部署失败!'
}
}
}
1.2 流水线说明
Git 拉取代码:
-
使用
git
步骤从指定的 Git 仓库拉取代码。请将url
和branch
替换为实际的仓库地址和分支名称。
Maven 编译打包:
-
使用
sh
步骤执行 Maven 命令mvn clean package
,编译并打包项目。
推送包到目标服务器:
-
使用
sshPublisher
插件将打包后的文件推送到目标服务器。需要提前在 Jenkins 中配置 SSH 服务器信息(configName
)。
执行部署脚本:
-
使用
sshCommand
插件在目标服务器上执行部署脚本。请确保目标服务器上有相应的脚本文件,并具有可执行权限。
2.流水线拆解说明
2.1 指定Jenkins 节点上运行
2.1.1 指定整个 Pipeline 在特定节点上运行
如果希望整个 Pipeline 在某个特定节点上运行,可以在 pipeline
块中使用 agent
指令。
示例 1:指定节点名称
pipeline {
agent { label 'node1' } // 指定在名为 'node1' 的节点上运行
stages {
stage('Example') {
steps {
sh 'echo Running on node1'
}
}
}
}
示例 2:指定节点标签
pipeline {
agent { label 'linux' } // 指定在标签为 'linux' 的节点上运行
stages {
stage('Example') {
steps {
sh 'echo Running on a Linux node'
}
}
}
}
2.1.2 指定某个阶段在特定节点上运行
如果希望某个阶段在特定节点上运行,可以在该阶段中使用 agent
指令。
示例 1:指定阶段在特定节点上运行
pipeline {
agent any // 默认在任意可用节点上运行
stages {
stage('Stage 1') {
agent { label 'node1' } // 指定在名为 'node1' 的节点上运行
steps {
sh 'echo Running Stage 1 on node1'
}
}
stage('Stage 2') {
agent { label 'node2' } // 指定在名为 'node2' 的节点上运行
steps {
sh 'echo Running Stage 2 on node2'
}
}
}
}
示例 2:动态选择节点
如果需要根据某些条件动态选择节点,可以使用 agent
的 script
块。
pipeline {
agent any
stages {
stage('Dynamic Node Selection') {
agent {
script {
// 根据条件动态选择节点
if (env.BRANCH_NAME == 'master') {
return 'node1'
} else {
return 'node2'
}
}
}
steps {
sh 'echo Running on dynamically selected node'
}
}
}
}
2.2 参数化构建
2.2.1 pipeline 在当构建参数为文件时
需要安装 File Parameter Plugin ,此插件提供了与 Pipeline 兼容的文件参数功能
-
Base64 File Parameter
适用于小文件,因为它会将文件内容编码为 Base64 字符串存储在环境变量中。 -
Stashed File Parameter
可实现上传大文件。
2.2.2 Base64 File Parameter用法示例
pipeline {
agent any
parameters {
base64File 'UPLOAD_FILE'
}
stages {
stage('Example') {
steps {
withFileParameter('UPLOAD_FILE') {
sh 'cat $UPLOAD_FILE'
}
}
}
}
}
2.2.3 Stashed File Parameter
2.2.3.1 用法示例
pipeline {
agent any
parameters {
stashedFile name: 'deployPackage', description: 'Upload a file'
}
environment {
UPLOAD_DIR = "${env.WORKSPACE}/upload/${env.BUILD_NUMBER}"
}
stage('处理上传的文件') {
steps {
script {
// 获取文件的原始名称
def originalFilename = env.deployPackage_FILENAME
echo "Original filename: ${originalFilename}"
// 创建目标目录
sh "mkdir -p ${UPLOAD_DIR}"
def targetPath = "${UPLOAD_DIR}/${originalFilename}"
// 解压文件
unstash 'deployPackage'
//将文件重命名为原始文件名
sh "mv deployPackage ${targetPath}"
}
}
}
}
2.2.3.2 文件上传大小限制修改
要调整 Jenkins 文件上传的大小限制,可以通过修改 Jenkins 的 web.xml
文件来实现。以下是详细步骤:
-
找到
web.xml
文件的位置-
如果你使用的是 Jenkins 的默认安装方式,
web.xml
文件通常位于 Jenkins 安装目录下的WEB-INF
文件夹中。编辑web.xml
文件
-
打开
web.xml
文件,找到
标签。如果该标签不存在,可以手动添加。 -
修改
标签的值,将其设置为你希望的大小(单位为字节)。例如,将限制设置为 500MB:524288000 这里的值是 500MB 转换为字节的结果(500 * 1024 * 1024)。
-
-
保存并重启 Jenkins
-
保存修改后的
web.xml
文件。 -
重启 Jenkins 服务,使更改生效。
-
2.3 环境变量的处理
environment {
// 定义环境变量
MAVEN_HOME = tool 'Maven3.8.1' // 已配置的 Maven 工具
PATH = "${MAVEN_HOME}/bin:${env.PATH}"
}
2.4 Jenkins 凭据管理处理 Git 认证
stage('拉取代码') {
steps {
// 使用凭据拉取代码
git branch: 'main', //指定分支
credentialsId: 'your-git-credentials-id', // 使用 Jenkins 中配置的 Git 凭据 ID
url: 'https://github.com/your-repo-url.git'
}
}
2.5 使用 Publish Over SSH 插件将文件推送到目标服务器
stage('推送包到目标服务器') {
steps {
// 使用 Publish Over SSH 插件将打包后的文件推送到目标服务器
sshPublisher(publishers: [sshPublisherDesc(configName: 'ssh_server_name', // 使用 Jenkins 中配置的 SSH Server 名称
transfers: [sshTransfer(sourceFiles: "target/${env.ARTIFACT_NAME}", // 打包后的文件路径
remoteDirectory: "/root/aa/${env.BUILD_NUMBER}", // 目标服务器上的目录
removePrefix: 'target', // 移除本地路径前缀
execCommand: "mkdir -p /root/aa/${env.BUILD_NUMBER}" // 在目标服务器上创建目录
)],
usePromotionTimestamp: false,
useWorkspaceInPromotion: false,
verbose: false)])
}
}
2.6 使用SSH Key 访问目标服务器
2.6.1 SSHPut推送文件到目标服务器
stage('上传文件到服务器') {
steps {
script {
def remote = [name : env.HOST_NAME,
host : env.HOST,
user : env.HOST_USER,
identityFile : env.IDENTITY_FILE,
allowAnyHosts: true]
def originalFilename = env.deployPackage_FILENAME
def targetPath = "${UPLOAD_DIR}/${originalFilename}"
sshPut remote: remote, from: targetPath, into: env.REMOTE_PATH
}
}
}
2.6.2 SSHCommand在目标服务器执行命令
stage('执行部署脚本') {
steps {
script {
def remote = [name : env.HOST_NAME,
host : env.HOST,
user : env.HOST_USER,
identityFile : env.IDENTITY_FILE,
allowAnyHosts: true]
sshCommand remote: remote, command: "cd ${env.REMOTE_PATH_APP} && sh deploy.sh"
}
}
}
2.7 post
块的常见用法
2.7.1 always
无论 Pipeline 的执行结果如何,都会执行的步骤。
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'echo Building...'
}
}
}
post {
always {
echo 'This will always run.'
}
}
}
2.7.2 success
仅当 Pipeline 成功完成时执行的步骤。
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'echo Building...'
}
}
}
post {
success {
echo 'This will run only if the pipeline succeeds.'
}
}
}
2.7.3 failure
仅当 Pipeline 失败时执行的步骤。
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'echo Building...'
sh 'exit 1' // 模拟失败
}
}
}
post {
failure {
echo 'This will run only if the pipeline fails.'
}
}
}
2.7.4 unstable
仅当 Pipeline 的结果为不稳定(例如测试失败但未导致构建失败)时执行的步骤。
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'echo Building...'
}
}
stage('Test') {
steps {
sh 'echo Running tests...'
sh 'exit 1' // 模拟测试失败
}
}
}
post {
unstable {
echo 'This will run only if the pipeline is unstable.'
}
}
}
2.7.5 aborted
仅当 Pipeline 被手动终止时执行的步骤。
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'echo Building...'
}
}
}
post {
aborted {
echo 'This will run only if the pipeline is aborted.'
}
}
}
2.7.6 cleanup
无论 Pipeline 的执行结果如何,都会执行的步骤,通常用于清理工作。
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'echo Building...'
}
}
}
post {
cleanup {
echo 'This will run as a cleanup step.'
sh 'rm -rf build/*'
}
}
}
2.7.7 综合示例
以下是一个包含多种条件的 post
块的完整示例:
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'echo Building...'
}
}
stage('Test') {
steps {
sh 'echo Running tests...'
sh 'exit 1' // 模拟测试失败
}
}
}
post {
always {
echo 'This will always run.'
}
success {
echo 'This will run only if the pipeline succeeds.'
}
failure {
echo 'This will run only if the pipeline fails.'
}
unstable {
echo 'This will run only if the pipeline is unstable.'
}
aborted {
echo 'This will run only if the pipeline is aborted.'
}
cleanup {
echo 'This will run as a cleanup step.'
sh 'rm -rf build/*'
}
}
}
2.7.8 注意事项
-
多个条件块:
-
如果多个条件块都匹配,它们会按顺序执行。
-
例如,如果 Pipeline 失败,
failure
和always
块都会执行。
-
-
cleanup
的特殊性:-
cleanup
块通常用于清理工作,无论 Pipeline 的执行结果如何,都会执行。 -
它可以与其他条件块一起使用。
-
-
灵活性:
-
post
块非常灵活,可以根据实际需求定义多个条件块,以满足不同的场景。
-