Home > Software design >  variable does not get resolved in my jenkinsfile
variable does not get resolved in my jenkinsfile

Time:09-29

I am new to jenkins/groovy and I am currently facing following issue...

I defined a deployment pipeline in a jenkinsfile, it consists in deploying scripts on two different environments running under linux. Deployment script copy_files.sh has to run under a specific user to preserve permissions:

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>'
                }
            }
        }
    } 
}

I defined the destination path where files are supposed to be copied as a variable (my_dst same on both envs). While the env variable $WORKSPACE gets resolved my variable my_dst does not, resulting in an abort of the copy_files.sh script because of missing argument... How can I quote my command properly in order my variable to be resolved? running sudo command with hard-coded destination path /opt/scripts works.

txs in advance

CodePudding user response:

So you want Groovy to inject the my_dst, but the WORKSPACE to come from the shell environment, so you will need to use double quotes (so groovy does the templating), and escape the $ in WORKSPACE so Groovy doesn't template it and it gets passed to the shell as-is:

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