Michael Butler
Michael Butler

Reputation: 6309

How do I run a Jenkins Pipeline stage only on specifically matched branch names?

I'd like to only run a stage in a Jenkins pipeline (Jenkinsfile) if the branch matches a specific regular expression (regex).

Something like:

pipeline {
...
stages {
  stage('Test') {
    when {
        // pseudo code
        branch name == regex(/^foo.*bar/)
    }
  }
}
...
}

Upvotes: 1

Views: 5509

Answers (1)

Michael Butler
Michael Butler

Reputation: 6309

The way to do this is by using the expression section combined with the ~== operator (which returns a boolean).

def branch_name = "${BRANCH_NAME}"
pipeline {
...
stages {
  stage('Test') {
    when {
        expression {
            // use !(expr) to negate something, || for or, && for and
            return branch_name =~ /^foo.*bar/

        }
    }
  }
}
...
}

Upvotes: 3

Related Questions