Home > OS >  Access string variable from bash in jenkinsfile groovy script
Access string variable from bash in jenkinsfile groovy script

Time:10-15

I'm building several android apps in a docker image using gradle and a bash script. The script is triggered by jenkins, which runs the docker image. In the bash script I gather information about the successes of the builds. I want to pass that information to the groovy script of the jenkinsfile. I tried to create a txt file in the docker container, but the groovy script in the jenkinsfile can not find that file. This is the groovy script of my jenkinsfile:

script {
    try {
        sh script:'''
        #!/bin/bash
        ./jenkins.sh
        '''
    } catch(e){
        currentBuild.result = "FAILURE"
    } finally {
        String buildResults = null
        try {
            def pathToBuildResults="[...]/buildResults.txt"
            buildResults = readFile "${pathToBuildResults}"
        } catch(e) {
            buildResults = "error receiving build results. Error: "   e.toString()
        } 
    }
}

In my jenkins.sh bash script I do the following:

[...]
buildResults =" $appName: Build Failed!" //this is done for several apps
echo "$buildResults" | cat > $pathToBuildResults //this works I checked, if the file is created
[...]

The file is created, but groovy cannot find it. I think the reason is, that the jenkins script does not run inside the docker container.

How can I access the string buildResults of the bash script in my groovy jenkins script?

CodePudding user response:

One option that you have in order to avoid the need to read the results file is to modify your jenkins.sh script to print the results to the output instead of writing them to a file and then use the sh step to capture that output and use it instead of the file.
Something like:

script {
    try {
        String buildResults = sh returnStdout: true, script:'''
           #!/bin/bash
           ./jenkins.sh
           '''
        // You now have the output of jenkins.sh inside the buildResults parameter
    } catch(e){
        currentBuild.result = "FAILURE"
    }
}

This way you are avoiding the need to handle the output files and directly get the results you need, which you can then parse and use however you need.

  • Related