Reputation: 3381
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?
Upvotes: 7
Views: 5708
Reputation: 381
I recently ran into this myself. ${env}
is not accessible in the options
block, but ${currentBuild}
is. So what I did was first was println("$currentBuild")
and get the name of the class. From that, I googled the Java source code docs and followed the functions until I got what I needed.
In my case, I wanted the ${env.NODE_NAME}
and I ended up with ${currentBuild.getRawBuild().getExecutor().getOwner().getDisplayName()}
Upvotes: 4
Reputation: 2683
You could just use lock
as a step
instead of an option
:
pipeline {
environment {
BRANCH = 'master'
}
agent any
stages{
stage('stage') {
steps {
lock("lock-${env.BRANCH}" as String) {
echo "${env.BRANCH}" as String
}
}
}
}
}
As within steps
the variable env.BRANCH
is set, this should work.
Also see documentation for lock
step.
Upvotes: 5