6

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"
    ^
6

You need to define variables before the pipeline block starts. Then it should be work.

def foo = "foo"

pipeline {
    agent none
    stages {
        stage("first") {
            sh "echo ${foo}"
        }
    }
}
| improve this answer | |
10

The variable must be defined in a script section.

pipeline {
    agent none
    stages {
        stage("first") {
            script {
                 foo = "bar"
            }
            sh "echo ${foo}"
        }
    }
}
| improve this answer | |
2

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
            }
        }
    }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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