Search code examples
variablesjenkins

Jenkins - Pass a variable from a stage to a function inside another stage


in Jenkins, I want to pass value of a variable from a stage to a function (defined in library) in another stage. I tested with env variables, but the function will take the initial value of the variable. my jenkinsfile code is:

@Library('shared-library')_

pipeline {
  agent any
environment {
    TF_WORK_DIR = '.'
}

stages {
    stage('Set-Environment') {
        steps {
            script {
                println("----------------------------Init Script-----------------------------")
                TF_WORK_DIR = "file"
            }}
    }

    stage('Init') {
        steps {
            script{
                    println("TF_WORK_DIR in init is ${TF_WORK_DIR}")
                    if (TF_WORK_DIR != ".") {   
                            println("TF_WORK_DIR in if condition init is ${TF_WORK_DIR}")
                            function()
                    }
                    else {
            println("TF_WORK_DIR in else condition init is ${TF_WORK_DIR}")
                        function()
                    }      
            }
        }
    }
}}

My function is

def call(timeoutMinutes = 10) {

try {
    echo "TF_WORK_DIR inside function ${TF_WORK_DIR}"
} catch (Exception e) {
    currentBuild.result = 'FAILURE'
    echo "An error occurred: ${e.getMessage()}\n"
}}

Current output is

----------------------------Init Script-----------------------------
TF_WORK_DIR in TF init is file
TF_WORK_DIR in if condition TF init is file
TF_WORK_DIR inside function .

expected output

    ----------------------------Init Script-----------------------------
    TF_WORK_DIR in init is file
    TF_WORK_DIR in if condition init is file
    TF_WORK_DIR inside function file

I also tried to define the variable outside of pipeline instead of inside environment bloc, but it didn't work am I missing something? how to make the function to take the updated value of TF_WORK_DIR ?

Thank you.


Solution

  • I ended by changing my function code to accept a parameter and passed that variable as parameter. thank you.