Richlewis Richlewis - 12 days ago 13
Bash Question

Using variables in Groovy and Jenkins pipeline build

I have a Jenkins pipeline build that needs to obtain the commit id (sha), so from what i can see the only way to get this is by doing the following

sh "git rev-parse --long HEAD > .git/commit-id"
GIT_COMMIT = readFile('.git/commit-id')


I need to use the GIT_COMMIT var within a curl command but am having trouble using it

sh '''curl "https://api.github.com/repos/myRepo/myBuild/statuses/${GIT_COMMIT}"}"'''
sh '''curl "https://api.github.com/repos/myRepo/myBuild/statuses/GIT_COMMIT"}"'''


At the moment GIT_COMMIT is not being passed through, it is always blank, but yet if i echo it i get the value back

echo GIT_COMMIT
--long
12345678910


Can anyone advise on how i achieve what i require please

Thanks

UPDATE

I have tried the following but still no luck

sh '''GIT_COMMIT=$(git rev-parse HEAD)'''
sh '''curl "https://api.github.com/repos/myBuild/statuses/$GIT_COMMIT"'''

Fo. Fo.
Answer

I don't know if you need to break up your shell commands into individual statements, but if so then you don't need to surround single line scripts with triple quotes, single will do.

You can do what you need in a multiline without outputting to a file, this way:

sh """
    GIT_COMMIT=`git rev-parse HEAD`
    curl https://api.github.com/repos/myRepo/myBuild/statuses/\${GIT_COMMIT}
"""

If you need single statements then you can use the file method you started with, like this:

sh "echo `git rev-parse HEAD` > file.txt"

GIT_COMMIT = readFile('./file.txt');

sh "curl https://api.github.com/repos/myRepo/myBuild/statuses/$GIT_COMMIT"