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,700 points
4,665 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
• 10,610 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
0 votes
1 answer
0 votes
1 answer

How to setup which trigger email notification to email id's in Jenkins pipeline script at every stage?

Hi@Shashi, You need to install some plugins in ...READ MORE

answered Sep 18, 2020 in Jenkins by MD
• 95,440 points
3,137 views
+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
56,189 views
+15 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 27, 2018 in DevOps & Agile by DragonLord999
• 8,450 points
3,460 views
+2 votes
1 answer
+5 votes
3 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
• 10,610 points
117,134 views
0 votes
5 answers
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP