29

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"
    ^
Dima
  • 143
  • 8
Jay
  • 1,064
  • 2
  • 12
  • 21

2 Answers2

28

The variable must be defined in a script section.

pipeline {
    agent none
    stages {
        stage("first") {
            steps {
                 script {
                      foo = "bar"
                 }
                 sh "echo ${foo}"
            }
        }
    }
}
Veran
  • 3
  • 2
plmaheu
  • 401
  • 4
  • 3
8

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
            }
        }
    }
}
modle13
  • 191
  • 1
  • 4