1

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

ocki_docki
  • 13
  • 2
  • Try to use double quotes ´sh "/bin/sudo su -c ${WORKSPACE}/copy_files.sh ${WORKSPACE} ${my_dst} - "`. See also https://stackoverflow.com/a/69221701/10721630 – Melkjot Sep 28 '21 at 11:28

1 Answers1

1

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>"
tim_yates
  • 167,322
  • 27
  • 342
  • 338