4

I want to use some common value across different conditions in post section of pipeline hence I tried following -

1.

post {  
      script {
           def variable = "<some dynamic value here>"
      }
      failure{
           script{
                  "<use variable  here>"
           }
     }
     success{
          script{
                "<use variable  here>"
         }
    }
}

2

post {  
          def variable = "<some dynamic value here>"
          failure{
               script{
                      "<use variable  here>"
               }
         }
         success{
              script{
                    "<use variable  here>"
             }
        }
    }

But it results into compilation error.

Can you please suggest how I can declare a variable in post section which can be used across conditions?

Alpha
  • 13,320
  • 27
  • 96
  • 163
  • 1
    You can find a solution (global variable) here: https://stackoverflow.com/questions/58972250/value-returned-from-a-script-does-not-assigned-to-a-variable-declared-in-jenkins/58972645#58972645 – Michael Kemmerzell Nov 25 '19 at 11:50
  • within a string that was surrounded by single quotes and had json I had to add one of my variables like this: `''' +variablename+ '''` I can't remember where I found this answer but I don't see this format anywhere else on the web when doing similar searches. Yes, you need to include the 3 single quotes on either side, and yes you need to include the plus symbols, no idea why. – Post Impatica Jan 12 '23 at 17:17

1 Answers1

2

You could use always condition which is guaranteed to be executed before any other conditions like success or failure. If you want to store String value, you can use use env variable to store it (environment variable always casts given value to a string). Alternatively, you can define a global variable outside the pipeline and then initialize it with the expected dynamic value inside the always condition. Consider the following example:

def someGlobalVar

pipeline {
    agent any

    stages {
        stage("Test") {
            steps {
                echo "Test"
            }
        }
    }

    post {
        always {
            script {
                env.FOO = "bar"
                someGlobalVar = 23
            }
        }

        success {
            echo "FOO is ${env.FOO}"
            echo "someGlobalVar = ${someGlobalVar}"
        }
    }
}

Output:

Running on Jenkins in /home/wololock/.jenkins/workspace/pipeline-post-sections
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] echo
Test
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] script
[Pipeline] {
[Pipeline] }
[Pipeline] // script
[Pipeline] echo
FOO is bar
[Pipeline] echo
someGlobalVar = 23
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131