Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins save shell output to var

I'm trying to check the md5sum of a file and export the Okay to a var. Then check that var to mark its okay if its not then fail the build.

How do I go about saving the result of the md5checksum to a variable that I can check in Jenkins.

I found this earlier but it doesn't see to work. I get an error from jerkins anytime I try to run the script.

md5Check = sh( script: 'md5sum -c ${env.SSH_HOME}/MD5SUM.MD5', returnStdout: true ).trim()
sh "sudo ssh -i ${env.SSH_KEY} ${env.SSH_URL} -tt \"cd ${env.SSH_HOME}/; echo ${md5Check}\""

It doesn't like the first line at all. Is there another way to do this?

Error:

WorkflowScript: 44: Expected a step @ line 44, column 17.
               md5Check = sh "sudo ssh -i ${env.SSH_KEY} 
${env.SSH_URL} -tt \"cd ${env.SSH_HOME}/; md5sum -c 
${env.SSH_HOME}/MD5SUM.MD5;\""
               ^

1 error

at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)

UPDATE:

I was able to fix this with the 2 supplied answers below but now the sh command runs on the Jenkins side instead of through ssh.

I also found I needed to wrap the code in a script and node for it to run the script.

script{
    node(){
        unstash 'build'
        env.FAIL=sh([script: "md5sum -c ${env.SSH_HOME}/MD5SUM.MD5", returnStdout: true ]).trim()
        sh "sudo ssh -i ${env.SSH_KEY} ${env.SSH_URL} -tt \"cd ${env.SSH_HOME}/; echo ${env.FAIL}\""
    }
}

So with the echo ${env.FAIL} it calls the correct command now but cant find the file because I think its running it in Jenkins shell not the ssh.

UPDATE 2

Okay so if I move the ssh stuff into the defined script and then just call echo from Jenkins shell it will find the file on the remote server properly. Here is the final code I used.

script{
    node(){
        unstash 'build'
        env.FAIL=sh([script: "sudo ssh -i ${env.SSH_KEY} ${env.SSH_URL} -tt \"cd ${env.SSH_HOME}/; md5sum -c ${env.SSH_HOME}/MD5SUM.MD5\"", returnStdout: true ]).trim()
        sh "sudo echo ${env.FAIL}"
     }
}
like image 578
Derek Lawrence Avatar asked Jun 19 '17 18:06

Derek Lawrence


2 Answers

It looks like you're missing the inner array for running the script:

sh([ script: 'md5sum -c ${env.SSH_HOME}/MD5SUM.MD5', returnStdout: true ]).trim()

Whenever I've set variables using a script in a Jenkins scripted pipeline, I've done it like this:

env.V5_DIR = WORKSPACE + '/' + sh([script: "basename ${V5_GIT_URL} .git", returnStdout: true]).trim()
like image 131
Wimateeka Avatar answered Oct 17 '22 04:10

Wimateeka


I wonder if your issue is because in the first line you're using a single quote when there's a var inside rather than a double quote. i.e. try

md5Check = sh( script: "md5sum -c ${env.SSH_HOME}/MD5SUM.MD5", returnStdout: true ).trim()
like image 41
James Rawlings Avatar answered Oct 17 '22 04:10

James Rawlings