Reputation: 238
I'm trying to create a Jenkins pipeline where I in my first stage I define a variable in a sh shell script. Then I want to run the next stages using a "when" condition depending on the previous defined variable.
pipeline {
agent { label 'php71' }
stages {
stage('Prepare CI...') {
steps{
sh '''
# Get the comment that was made on the PR
COMMENT=`echo $payload | jq .comment.body | tr -d '"'`
if [ "$COMMENT" = ":repeat: Jenkins" ]; then
BUILD="build"
fi
'''
}
}
stage('Build Pre Envrionment') {
agent { label 'php71' }
when {
expression { return $BUILD == "build" }
}
steps('Build') {
sh '''
echo $BUILD
echo $COMMENT
'''
}
}
}
}
This gives me an error: groovy.lang.MissingPropertyException: No such property: $BUILD for class: groovy.lang.Binding
How can I do it? Is it possible? Thank you!
Upvotes: 1
Views: 4667
Reputation: 102
The problem is that the variable BUILD
is only available within the sh
block. but to use it later in the when
block it must be known globally in the pipeline. This is possible if you define BUILD
in the environment
block on pipeline
level. A possible solution for your problem see here:
pipeline {
agent { label 'php71' }
environment {
COMMENT=sh(script: '''# Get the comment that was made on the PR
echo $payload | jq .comment.body | tr -d '"'
''', returnStdout: true).trim()
BUILD=sh(script: '''# Get the comment that was made on the PR
COMMENT=`echo $payload | jq .comment.body | tr -d '"'`
if [ "$COMMENT" = ":repeat: Jenkins" ]; then
echo "build"
fi
''', returnStdout: true).trim()
}
stages {
stage('Build Pre Envrionment') {
agent { label 'php71' }
when {
expression { return env.BUILD == "build" }
}
steps('Build') {
sh '''
echo $BUILD
echo $COMMENT
'''
}
}
}
}
Upvotes: 0
Reputation: 7600
Probably use Jenkins scripted pipeline which is more flexible than declarative. Print the value in the sh script and use returnStdout to make it available to the pipeline script. See How to do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)? for more details.
Upvotes: 1