HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMajor

How to define variable in Jenkins declarative pipeline?

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
declarativejenkinsdefinehowvariablepipeline

Problem

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

Solution

The variable must be defined in a script section.

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

Code Snippets

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

Context

StackExchange DevOps Q#6126, answer score: 26

Revisions (0)

No revisions yet.