'How to define a variable in post section of pipeline?

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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Szymon Stepniak