主题
Jenkins 03 · 功能详解
四篇制:01 理论 · 02 部署 · 03 功能 · 04 实战 本篇是 Jenkinsfile 写法。架构见 01 理论。
一、声明式流水线完整结构
groovy
pipeline {
agent { label 'docker' }
environment {
REGISTRY = 'harbor.example.com'
IMAGE = "harbor.example.com/team/app:${env.GIT_COMMIT.take(12)}"
}
stages {
stage('Checkout') {
steps { checkout scm }
}
stage('Build & Push') {
steps {
withCredentials([usernamePassword(credentialsId: 'harbor-cred',
usernameVariable: 'USER', passwordVariable: 'PASS')]) {
sh 'echo $PASS | docker login $REGISTRY -u $USER --password-stdin'
sh 'docker build -t $IMAGE .'
sh 'docker push $IMAGE'
}
}
}
stage('Test') {
steps { sh 'npm ci && npm test' }
}
stage('Deploy') {
when { branch 'main' }
steps {
sh 'ansible-playbook -i inventory.yml deploy.yml -e image=$IMAGE'
}
}
}
post {
always { junit 'test-results/*.xml' }
failure { echo '构建失败,通知值班' }
success { echo '部署完成' }
}
}逐块的意义:
- agent:在哪跑(label 调度到对应 agent)。
- environment:环境变量,镜像 tag 用 commit SHA 保证可追溯。
- stages/steps:阶段顺序执行,每阶段若干步骤。
- when:条件触发(如只在 main 分支部署)。
- post:无论成败都跑的收尾(always 收测试报告、failure 告警)。
二、凭据管理
凭据存 Jenkins Credentials(加密),流水线用 withCredentials 注入,绝不把密码写进 Jenkinsfile。usernamePassword 注入用户名密码,string 注入 token,sshUserPrivateKey 注入 SSH 私钥。日志里凭据自动打码。
三、参数化与触发器
groovy
parameters {
choice(name: 'ENV', choices: ['staging','prod'], description: '部署环境')
booleanParam(name: 'SKIP_TEST', defaultValue: false)
}
triggers {
gitlab(triggerOnPush: true, branchFilterType: 'All') // GitLab webhook
// cron('H 2 * * *') // 定时构建
}参数化让一个 job 适配多环境;触发器接 webhook 实现 push 即构建。
四、共享库复用
多项目流水线雷同,抽成 Shared Library(独立 Git 仓库),@Library('my-lib') _ 引入,把公共逻辑写成 vars/函数,一处改处处生效——这是 Pipeline as Code 的复用精髓。
五、官方文档
- Pipeline 语法:https://www.jenkins.io/doc/book/pipeline/syntax/
- 凭据:https://www.jenkins.io/doc/book/using/using-credentials/
- 共享库:https://www.jenkins.io/doc/book/pipeline/shared-libraries/
黑公网安备23022102000118号