Jenkins管道脚本全局变量



我正在学习jenkins,并且正在研究一个示例管道

pipeline {
agent any
stages {
stage('Stage1') { 
steps {
bat  '''
cd C:/Users/roger/project/

python -u script1.py
'''
}
}
stage('Stage2') { 
steps {
bat  '''
cd cd C:/Users/roger/project/abc/

python -u script2.py
'''
}
}
stage('Stage3') { 
steps {
bat  '''
cd cd C:/Users/roger/project/abc/new_dir/

python -u demo.py
'''
}
}
}
}

是否有一种方法可以将项目C:/Users/roger/project/的基本路径存储为一个变量,以便它可以用来附加新的路径,而不是写入整个路径。

我怎么写上面的阶段,这样我就不必每次都重复写相同的基本路径到每个阶段

您有几个选项,最简单的方法是在environment指令(阅读更多)中定义参数,这将使该参数可用于管道中的所有阶段,并将其加载到任何解释器步骤的执行环境中,如sh,batpowershell,从而使该参数也可用于您执行的脚本作为环境变量。
此外,environment指令支持非常有用的凭据参数。
在你的例子中,它看起来像:

pipeline {
agent any
environment {
BASE_PATH = 'C:/Users/roger/project/'
}
stages {
stage('Stage1') {
steps {
// Using the parameter as a runtime environment variable with bat syntax %%
bat  '''
cd %BASE_PATH%
python -u script1.py
'''
}
}
stage('Stage2') {
steps {
// Using groovy string interpolation to construct the command with the parameter value
bat  """
cd ${env.BASE_PATH}abc/
python -u script2.py
"""
}
}
}
}

另一个选择是使用在管道顶部部分定义的全局变量,它的行为将像任何groovy变量一样,并且可用于管道中的所有阶段(但不适用于解释器步骤的执行环境)。
类似于:

BASE_PATH = 'C:/Users/roger/project/'
pipeline {
agent any
stages {
stage('Stage1') {
steps {
// Using the parameter insdie a dir step to change directory 
dir(BASE_PATH) {
bat 'python -u script1.py'
}
}
}
stage('Stage2') {
steps {
// Using groovy string interpolation to construct the command with the parameter value
bat  """
cd ${BASE_PATH}abc/
python -u script2.py
"""
}
}
}
}

最新更新