Error: ‘Jenkins: Cannot define variable in pipeline stage’

0 votes

I’m using the Jenkins pipeline feature to run a declarative pipeline in which I’m trying to define a variable:

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

I get the following error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 5: 
           def foo = "foo"
           ^
Aug 17, 2018 in Jenkins by Tyrion anex
• 8,360 points
1,717 views

3 answers to this question.

0 votes

Try this, you have to define an environment variable in order to do this.

pipeline {
   environment {
     FOO = "foo"
   }
   agent none
   stages {
       stage("first") {
           sh "echo ${FOO}"
      }
   }
}
answered Aug 17, 2018 by Sophie may
• 9,940 points
0 votes

You can create variables before the pipeline block starts.

For Example,

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

answered Jan 27, 2019 by anonymous
Hey, I have a small doubt. If variables are defined outside the pipeline are they like global variables?
0 votes
answered Mar 13, 2019 by Charles Wu
Yeah, I found this thread but I had a doubt but I didn't have enough reputations to comment there.
Tell me about it !!

Never been able to comment on stackoverflow... :(

Related Questions In Jenkins

0 votes
2 answers
+2 votes
3 answers

Permission denied error while running a simple job in Jenkins

Hey @Hannah, try changing the permissions using ...READ MORE

answered Oct 25, 2018 in Jenkins by krishti
13,665 views
0 votes
1 answer

Error: ‘Jenkins pipeline: No such DSL method'

This is a simple mistake, just remove ...READ MORE

answered Aug 17, 2018 in Jenkins by Sophie may
• 9,940 points
7,754 views
+13 votes
2 answers

Git management technique when there are multiple customers and need multiple customization?

Consider this - In 'extended' Git-Flow, (Git-Multi-Flow, ...READ MORE

answered Mar 26, 2018 in DevOps & Agile by DragonLord999
• 8,400 points
419 views
0 votes
1 answer
+2 votes
2 answers

How to trigger a Jenkins pipeline A in another Jenkins pipeline B?

You can run the following code, its ...READ MORE

answered Jul 5, 2018 in Jenkins by Sophie may
• 9,940 points
14,196 views
0 votes
5 answers