I want to execute some stage in loop. I have Jenkinsfile
pipeline {
agent any
tools {}
parameters {}
environment {}
stages {
stage('Execute') {
steps {
script {
for (int i = 0; i < hostnameMap.size; i++) {
hostname = hostnameMap[i]
echo 'Executing ' + hostname
stage('Backup previous build ' + hostname) {
backup(hostname, env.appHome)
}
stage('Deploy ' + hostname) {
when {
expression { env.BRANCH_NAME ==~ /(dev|master)/ }
}
steps {
script {
deploy(hostname , env.appHome, env.appName)
}
}
}
stage('Restart ' + hostname) {
when {
expression { env.BRANCH_NAME ==~ /(dev|master)/ }
}
steps {
script {
restart(hostname , env.appName, env.port)
}
}
}
}
}
}
}
}
}
But got error
java.lang.NoSuchMethodError: No such DSL method 'when' found among steps
Separately all of this stage works fine. Why I got this error?
Job DSL was one of the first popular plugins for Jenkins which allows managing configuration as code and many other plugins dealing with this aspect have been created since then, most notably the Jenkins Pipeline and Configuration as Code plugins.
The checkout step will checkout code from source control; scm is a special variable which instructs the checkout step to clone the specific revision which triggered this Pipeline run.
With JenkinsFile, you can write the steps needed for running a Jenkins pipeline. The benefits of using JenkinsFile are: You can create pipelines automatically for all branches and execute pull requests with just one JenkinsFile. You can review your Jenkins code on the pipeline.
agent. The agent directive specifies where the entire Pipeline, or a specific stage, will execute in the Jenkins environment depending on where the agent directive is placed. The directive must be defined at the top-level inside the pipeline block, but stage-level usage is optional.
stage('Execute') {
steps {
script {
for (int i = 0; i < hostnameMap.size; i++) {
hostname = hostnameMap[i]
echo 'Executing ' + hostname
stage('Backup previous build ' + hostname) {
backup(hostname, env.appHome)
}
stage('Deploy ' + hostname) {
if (env.BRANCH_NAME ==~ /(dev|master)/) {
deploy(hostname, env.appHome, env.appName)
}
}
stage('Restart ' + hostname) {
if (env.BRANCH_NAME ==~ /(dev|master)/) {
restart(hostname, env.appName, env.port)
}
}
}
}
}
}
when
is a directive used in the declarative pipeline definition - it won't work inside script {} block. Instead use if
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With