特性 | Declarative Pipeline 声明式 | Scripted Pipeline 脚本式 |
---|
语法 | 基于结构化 DSL,语法固定 | 基于 Groovy 脚本,更灵活 |
可读性 | 好,适合团队协作 | 灵活性强,但不易读 |
复杂逻辑处理 | 适合常规流程,有一定限制 | 可写复杂逻辑和控制结构 |
学习曲线 | 简单上手 | 需要掌握 Groovy |
错误提示 | 更明确,容易调试 | 错误提示偏底层 |
使用推荐 | 首选!90% 用 Declarative 就够 | 高级用法用 Scripted |
✅ Declarative 示例
pipeline {agent anystages {stage('Build') {steps {echo "Building..."}}stage('Test') {steps {echo "Testing..."}}}post {always {echo "Pipeline finished"}}
}
⚙️ Scripted 示例
node {try {stage('Build') {echo "Building..."}stage('Test') {echo "Testing..."}} finally {echo "Pipeline finished"}
}
🧠 适用场景建议
-
Declarative:
-
团队协作(代码可读性好)
-
常规 CI/CD 流程(编译/测试/部署)
-
配合 Jenkins UI 编辑器使用(比如 Blue Ocean)
-
-
Scripted:
-
构建逻辑特别复杂,比如循环、条件嵌套很多
-
需要使用 Groovy 高级特性(比如自定义类、闭包)
-
与外部系统做精细交互
-
💡 综合建议
除非你特别需要高级 Groovy 控制结构或动态构建流程,否则 建议优先使用 Declarative Pipeline,更稳定、更容易维护。
🟦 原始:Declarative Pipeline(声明式)
pipeline {agent {node {customWorkspace pipelineCustomWorkspace}}stages {stage('Example') {steps {dir("bar") {script {myFunction()sh("pwd")sh("ls")}}}}}post {always {archiveArtifacts "**/foo.json"}}
}
🟨 转换后的 Scripted Pipeline(脚本式)
String pipelineCustomWorkspace = "/jenkins/pipeline-${BRANCH_NAME}/${BUILD_NUMBER}"def myFunction() {def content = '{"foo":"bar"}'sh("echo '${content}' > foo.json")
}node {// 切换到自定义工作目录ws(pipelineCustomWorkspace) {try {stage('Example') {dir("bar") {myFunction()sh("pwd")sh("ls")}}} finally {archiveArtifacts artifacts: "**/foo.json", fingerprint: true}}
}
🧠 对照说明:
内容 | 声明式 | 脚本式 |
---|---|---|
指定 Agent / Node | agent 块 | node {} 块 |
自定义工作目录 | customWorkspace | ws() 包裹在 node 中 |
阶段和目录切换 | stage + dir + script | stage {} + dir() 组合 |
后置操作如归档文件 | post { always { archiveArtifacts }} | finally { archiveArtifacts } |