Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a value from Jenkins function to the build stage?

I want to return the value from groovy function back to my jenkins build stage so that the value can be used as a condition in other stages. I am not able to figure out how to implement this. I have tried something like below but that didn't work.

I have Jenkinsfile something like this:

pipeline
{
  agent any
  stages
  {
       stage('Sum')
       {
         steps
         {
          output=sum()
          echo output
         }
       }
       stage('Check')
       {
         when
         {
          expression
          {
           output==5
          }
         }
         steps
         {
          echo output
         }
       }
  }
}

def sum()
{
   def a=2
   def b=3
   def c=a+b
   return c
}

The above approach doesn't work. Can someone provide correct implementation.

like image 514
jason_1093 Avatar asked Oct 21 '25 03:10

jason_1093


1 Answers

You are missing a script-step. It is necessary if you want to execute plain groovy in your Jenkinsfile. Furthermore output has to be set as global variable if you want to access it later.

def output // set as global variable
pipeline{
...

stage('Sum')
{
    steps
    {
        script
        {
            output = sum()
            echo "The sum is ${output}"
        }
    }
}
...
like image 155
Michael Kemmerzell Avatar answered Oct 24 '25 05:10

Michael Kemmerzell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!