jenkins pipeline script for
时间: 2025-05-25 19:08:35 浏览: 21
### Jenkins Pipeline 脚本示例与编写指南
Jenkins Pipeline 提供了两种主要类型的定义方式:声明式管道 (Declarative Pipeline) 和脚本式管道 (Scripted Pipeline)[^1]。这两种方式各有优劣,其中声明式管道更适合初学者使用,而脚本式管道则提供了更高的灵活性。
#### 声明式管道 (Declarative Pipeline)
以下是一个简单的声明式管道示例:
```groovy
pipeline {
agent any
stages {
stage('Checkout') {
steps {
git 'https://github.com/example/repo.git' // 替换为实际的Git仓库地址[^2]
}
}
stage('Build') {
steps {
sh 'mvn clean package' // 使用Maven进行构建
}
}
stage('Test') {
steps {
script {
build job: 'example-job', parameters: [
[$class: 'StringParameterValue', name: 'PARAM_NAME', value: 'paramValue']
] // 构建其他Job并传递参数[^3]
}
}
}
}
}
```
此示例展示了如何从版本控制系统拉取代码、运行构建命令以及触发另一个带有参数的任务。
#### 脚本式管道 (Scripted Pipeline)
对于需要更高自由度的情况,可以采用脚本式管道。下面是一段脚本式管道的例子:
```groovy
node {
stage('Clone Repository') {
checkout scm: [$class: 'GitSCM', branches: [[name: '*/main']], userRemoteConfigs: [[url: 'https://github.com/example/repo.git']]] // 自定义分支名称和远程URL
}
stage('Run Tests') {
def testResult = sh(script: 'pytest tests/', returnStatus: true) // 运行测试框架Pytest
if (testResult != 0) {
error 'Tests failed!'
}
}
stage('Deploy') {
echo 'Deployment logic goes here...'
}
}
```
这段脚本实现了克隆指定存储库的功能,并通过 `sh` 步骤执行 Python 测试套件。如果测试失败,则会终止流水线。
---
#### 高级功能扩展
为了实现更复杂的工作流,比如动态设置环境变量或者条件判断逻辑,可以通过 Groovy 编程语言完成这些需求。例如:
```groovy
pipeline {
agent any
environment {
ENV_VAR = 'value'
}
stages {
stage('Conditional Stage') {
when {
expression { return params.RUN_TESTS.toBoolean() } // 判断是否运行特定阶段[^3]
}
steps {
echo "Running conditional step..."
}
}
}
}
```
在此处,`when` 关键字允许基于表达式的条件控制某些阶段的行为。
---
#### 工具辅助开发
除了手动编写外,还可以利用 **Pipeline Syntax Generator** 自动生成部分常用步骤的代码片段。访问 Jenkins Web UI 中对应 Job 页面下的 “Pipeline Syntax” 功能即可快速生成所需指令。
---
阅读全文
相关推荐



















