23

I defined variable in declarative Jenkins pipeline script but having issues with simple variable declaration.

Here is my script:

pipeline {
    agent none
    stages {
        stage("first") {
            def foo = "foo" // fails with "WorkflowScript: 5: Expected a step @ line 5, column 13."
            sh "echo ${foo}"
        }
    }
}

but it's shows error:

org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed:
WorkflowScript: 5: Expected a step @ line 5, column 13.
    def foo = "foo"
    ^
2

2 Answers 2

26

The variable must be defined in a script section.

pipeline {
    agent none
    stages {
        stage("first") {
            steps {
                 script {
                      foo = "bar"
                 }
                 sh "echo ${foo}"
            }
        }
    }
}
7

You can also use environment block to inject an environment variable.

(Side note: sh is not needed for echo)

pipeline {
    agent none
    environment {
        FOO = "bar"
    }
    stages {
        stage("first") {
            steps {
                echo "${env.FOO}"
                // or echo "${FOO}"
            }
        }
    }
}

You can even define the env var inside the stage block to limit the scope:

pipeline {
    agent none
    stages {
        stage("first") {
            environment {
                FOO = "bar"
            }
            steps {
                // prints "bar"
                echo "${env.FOO}"
                // or echo "${FOO}"
            }
        }
        stage("second") {
            steps {
                // prints "null"
                echo "${env.FOO}"
                // or echo "${FOO}", pipeline would fail here
            }
        }
    }
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.