六、【Pipeline流水线】when语法、input使用、Groovy postbuild、jenkinsfile的存储方式 小杨_老师 2025年05月15日 预计阅读 3 分钟 原文 ### when语法 - when: 根据条件判断流水线的执行 - anyOf: 多个条件中任意一个满足时则执行相应的操作 - expression: 用于执行自定义表达式并检查其返回值是否为真 - equals expected: 用于比较两个值是否相等 ```groovy pipeline { agent any environment { DEPLOY_TO = 'production' } stages { stage('Example Build') { steps { echo 'Hello World' } } stage('Example Deploy') { when { anyOf { environment name: 'DEPLOY_TO', value: 'production' expression { BRANCH_NAME ==~ /(production|master)/ } expression { return params.BUILD.NUMBER >= 1 } } } steps { echo 'Deploying' } } } } pipeline { agent any parameters { choice choices: ['master', 'pre', 'test'], name: 'build_branch' } stages { stage('deploy') { when { not { equals expected: build_branch, actual: 'master' } } steps { echo "deploy success" } } } } ``` ### input使用 - 使用input可以对构建进行审核发布 ```groovy pipeline { agent any stages { stage('Example') { input { message "这个构建你自已确认吗?" ok "是的,我确认." parameters { string(name: 'PERSON', defaultValue: '我要发布', description: '你是为什么什么原因要构建呢?') } } steps { echo "Hello, ${PERSON}, nice to meet you." } } } } ``` ### Groovy postbuild - Groovy 脚本作为构建后操作 - 安装插件Groovy postbuild ```groovy pipeline { agent any stages { stage('test') { steps { echo "success" } } } post { success { script { manager.addShortText("构建用户:${BUILD_USER}") } } } } ``` ### jenkinsfile的存储方式 - 将Jenkinsfile与业务代码存放于一个仓库 - Jenkinsfile与业务代码仓库分离 #### 流水线指定代码仓库 - 配置git仓库地址 - 在另外gitlab服务器创建一个只存jenkinsfile的项目jenkinsfile,在项目下创建一个目录:`go-1`,目录下创建Jenkinsfile文件 - 流水线中定义选择:Pipeline script from SCM - SCM:Git,Repositories URL: http://192.168.120.134/jenkins/jenkinsfile.git ,补充密钥 - 指定分支: */main,脚本路径:`go-1/Jenkinsfile` - git仓库创建目录与Jenkinsfile - 如果业务代码和Jenkinsfile分开了,同时又配置了` skipDefaultCheckout()`,此时更新后不会再拉取Jenkinsfile文件了,此时需要checkout scm来实现 ```groovy steps { cleanWs() checkout scm ... } ```
评论区