如何将 Jenkinsfile 配置为仅 运行 在 运行 执行每日 cron 作业时的特定阶段?
How to configure Jenkinsfile to only run a specific stage when running a daily cron job?
我每晚都将 cron 作业设置为 运行,但我只希望它在 Jenkinsfile 中的 运行 阶段 B 而不是全部。
pipeline {
agent any
triggers {
cron('@midnight')
}
}
stages {
stage('A') {
...
}
stage('B'){
when {
allOf {
expression { env.CHANGE_TARGET == "master" }
branch "PR-*"
}
}
steps {
sh """
echo 'running script'
make run-script
"""
}
}
stage('C') {
...
}
如果不删除阶段 B 中的条件,我似乎无法弄清楚如何将 cron 明确指定为仅 运行 Jenkinsfile 的阶段 B - 我需要 运行 该 makefile仅在满足这些条件时或在每日午夜 cron 作业期间编写脚本
您可以使用 Parameterized Scheduler Plugin 来实现您想要的,它使您能够定义使用特定环境变量触发作业的 cron 触发器,然后您可以使用此变量作为条件来确定要执行的步骤.
在您的情况下,您可以在每个阶段的 when
指令中使用该环境变量来根据变量确定它是否应该 运行 。
类似于:
pipeline {
agent any
parameters {
booleanParam(name: 'MIDNIGHT_BUILD', defaultValue: 'true', description: 'Midnight build')
}
triggers {
parameterizedCron('''
0 * * * * %MIDNIGHT_BUILD=true
''')
}
stages {
stage('A') {
when {
expression { !env.MIDNIGHT_BUILD }
}
steps {
...
}
}
stage('B') {
when {
expression { env.MIDNIGHT_BUILD || env.CHANGE_TARGET == "master" }
}
steps {
sh """
echo 'running script'
make run-script
"""
}
}
stage('C') {
when {
expression { !env.MIDNIGHT_BUILD }
}
steps {
...
}
}
}
}
我每晚都将 cron 作业设置为 运行,但我只希望它在 Jenkinsfile 中的 运行 阶段 B 而不是全部。
pipeline {
agent any
triggers {
cron('@midnight')
}
}
stages {
stage('A') {
...
}
stage('B'){
when {
allOf {
expression { env.CHANGE_TARGET == "master" }
branch "PR-*"
}
}
steps {
sh """
echo 'running script'
make run-script
"""
}
}
stage('C') {
...
}
如果不删除阶段 B 中的条件,我似乎无法弄清楚如何将 cron 明确指定为仅 运行 Jenkinsfile 的阶段 B - 我需要 运行 该 makefile仅在满足这些条件时或在每日午夜 cron 作业期间编写脚本
您可以使用 Parameterized Scheduler Plugin 来实现您想要的,它使您能够定义使用特定环境变量触发作业的 cron 触发器,然后您可以使用此变量作为条件来确定要执行的步骤.
在您的情况下,您可以在每个阶段的 when
指令中使用该环境变量来根据变量确定它是否应该 运行 。
类似于:
pipeline {
agent any
parameters {
booleanParam(name: 'MIDNIGHT_BUILD', defaultValue: 'true', description: 'Midnight build')
}
triggers {
parameterizedCron('''
0 * * * * %MIDNIGHT_BUILD=true
''')
}
stages {
stage('A') {
when {
expression { !env.MIDNIGHT_BUILD }
}
steps {
...
}
}
stage('B') {
when {
expression { env.MIDNIGHT_BUILD || env.CHANGE_TARGET == "master" }
}
steps {
sh """
echo 'running script'
make run-script
"""
}
}
stage('C') {
when {
expression { !env.MIDNIGHT_BUILD }
}
steps {
...
}
}
}
}