变量在我的jenkinsfile中没有得到解析



我是新来的jenkins/groovy,我目前面临以下问题…

我在jenkinsfile中定义了一个部署管道,它包含在linux下运行的两个不同环境中部署脚本。部署脚本copy_files.sh必须在特定用户下运行以保留权限:

def my_dst = '/opt/scripts'
pipeline {
agent { label '<a generic label>' }
stages {
stage('Deployment env1') {
agent { label '<a specific label>' }
steps {
script {
echo 'Deploying scripts...'
sh '/bin/sudo su -c "${WORKSPACE}/copy_files.sh ${WORKSPACE} ${my_dst}" - <another user>'
}
}
}
stage('Deployment env2') {
agent { label '<another specific label>' }
steps {
script {
echo 'Deploying scripts...'
sh '/bin/sudo su -c "${WORKSPACE}/copy_files.sh ${WORKSPACE} ${my_dst}" - <another user>'
}
}
}
} 
}

我定义了目标路径,其中文件应该被复制为一个变量(my_dst在两个envs上相同)。当env变量$WORKSPACE得到解析时,我的变量my_dst没有得到解析,导致copy_files.sh脚本因为缺少参数而中止…我怎样才能正确地引用我的命令,以便我的变量被解析?在硬编码的目标路径/opt/scripts下运行sudo命令可以工作。

txs提前

所以你想让Groovy注入my_dst,但WORKSPACE来自shell环境,所以你需要使用双引号(这样Groovy就会进行模板化),并在WORKSPACE中转义$,这样Groovy就不会模板化它,它被原样传递给shell:

sh "/bin/sudo su -c "${WORKSPACE}/copy_files.sh ${WORKSPACE} ${my_dst}" - <another user>"

最新更新