26

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
  • 994
  • 2
  • 10
  • 20
  • You may have to enclose the shell script command within the 'Step' similar to 'Stage'. Refer: https://jenkins.io/doc/book/pipeline/syntax/ – Karthik Venkatesan Mar 07 '19 at 03:14
  • same question post as: https://stackoverflow.com/questions/39832862/cannot-define-variable-in-pipeline-stage – Nor.Z Nov 15 '23 at 07:45

2 Answers2

26

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
  • 381
  • 3
  • 3
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
            }
        }
    }
}
modle13
  • 181
  • 1
  • 4
  • 1
    You can use dynamic code in the environment block. https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#setting-environment-variables-dynamically – Steve Mitchell Feb 01 '22 at 01:36