I have a declarative Jenkins Pipeline with a lock, e. g.
pipeline {
environment {
BRANCH = 'master'
}
agent any
stages{
stage('stage') {
options {
lock(resource: "lock-${env.BRANCH}")
}
steps {
echo "Something"
}
}
}
}
But when I execute the pipeline, in the log it says
[Pipeline] lock
Trying to acquire lock on [lock-null]
Lock acquired on [lock-null]
[Pipeline] {
[Pipeline] echo
master
[Pipeline] }
Lock released on resource [lock-null]
The environment variable seems to be not set when the lock-name is evaluated, but when the echo argument is evaluated, it is set correctly.
This answer to a somewhat related question gave the hint to use a lazily evaluated GString instead of a normal GString. Trying this:
pipeline {
environment {
BRANCH = 'master'
}
agent any
stages{
stage('stage') {
options {
lock(resource: "lock-${->env.BRANCH}" as String)
}
steps {
echo "${->env.BRANCH}" as String
}
}
}
}
gives me the following log messages
[Pipeline] lock
Trying to acquire lock on [[no resource/label specified - probably a bug]]
Lock acquired on [[no resource/label specified - probably a bug]]
[Pipeline] {
[Pipeline] echo
master
[Pipeline] }
Lock released on resource [[no resource/label specified - probably a bug]]
So, it looks like the variable can't be resolved correctly.
The problem I want to solve is, creating a multibranch-pipeline which has a lock on a stage. But when the lock has a name, which is not dependend on the branchname, only one branch of the pipeline can run in parallel in this stage.
How can I solve this?