Jenkins:在 shell 脚本中循环遍历 JSON 列表
Jenkins : Loop over a JSON List inside a shell script
{
"TEST_SCRIPTS":["test_1.py","test_2.py"],
"TEST_SCRIPTS1":"test_1.py;test_2.py"
}
这个 json 文件,我使用 :
加载到我的 Jenkins 管道中
def load_config(){
def config = readJSON file "./test.json"
return config
}
现在,我需要 shell 脚本中的循环,它可以执行 TEST_SCRIPTS & TEST_SCRIPTS1.
中定义的每个 python 文件
stage('Test') {
steps {
script{
config = load_config()
sh """
conda env create -n test_env_py37 -f conda.yaml
conda activate test_env_py37
// Below loop is not working. This env is huge, and mendatory for below code to run
for test_script in ${config.TEST_SCRIPTS};
do
python "$test_script"
done
for test_script in ${config.TEST_SCRIPTS1};
do
python "$test_script"
done
"""
}
}
}
您可以使用 groovy 方法而不是 shell 方法,并使用 groovy 功能完成所有解析逻辑。
类似于:
stage('Test') {
steps {
script {
def config = readJSON file "./test.json"
def testScripts = config.TEST_SCRIPTS.collect { "python \"$it\""}.join("\n")
def testScripts1 = config.TEST_SCRIPTS1.split(';').collect { "python \"$it\""}.join("\n")
sh """
conda env create -n test_env_py37 -f conda.yaml
conda activate test_env_py37
${testScripts}
${testScripts1}
"""
}
}
}
{
"TEST_SCRIPTS":["test_1.py","test_2.py"],
"TEST_SCRIPTS1":"test_1.py;test_2.py"
}
这个 json 文件,我使用 :
加载到我的 Jenkins 管道中 def load_config(){
def config = readJSON file "./test.json"
return config
}
现在,我需要 shell 脚本中的循环,它可以执行 TEST_SCRIPTS & TEST_SCRIPTS1.
中定义的每个 python 文件stage('Test') {
steps {
script{
config = load_config()
sh """
conda env create -n test_env_py37 -f conda.yaml
conda activate test_env_py37
// Below loop is not working. This env is huge, and mendatory for below code to run
for test_script in ${config.TEST_SCRIPTS};
do
python "$test_script"
done
for test_script in ${config.TEST_SCRIPTS1};
do
python "$test_script"
done
"""
}
}
}
您可以使用 groovy 方法而不是 shell 方法,并使用 groovy 功能完成所有解析逻辑。
类似于:
stage('Test') {
steps {
script {
def config = readJSON file "./test.json"
def testScripts = config.TEST_SCRIPTS.collect { "python \"$it\""}.join("\n")
def testScripts1 = config.TEST_SCRIPTS1.split(';').collect { "python \"$it\""}.join("\n")
sh """
conda env create -n test_env_py37 -f conda.yaml
conda activate test_env_py37
${testScripts}
${testScripts1}
"""
}
}
}