Robert
Robert

Reputation: 7053

Regex in Jenkins pipeline

I'm trying to create a Jenkins pipeline step that should only run for certain Gerrit projects. In particular, for all projects where the variable GERRIT_PROJECT starts with "platform/zap". Sadly, I suffer from a lack of skills in Groovy.

This is what I got so far:

stage ('zap') {
        when {
            expression {
                isMatch = env.GERRIT_PROJECT =~ /^platform\/zap/
                return isMatch
            }
        }
        steps {
            build job: 'Zap', parameters: [
                string(name: 'ZAP_PROJECT', value: env.GERRIT_PROJECT)
            ]
        }
    }

In other words, the stage should be executed for "platform/zap/os" but not for "app/hello".

Any guidance would be greatly appreciated.

Upvotes: 4

Views: 6482

Answers (2)

Szymon Stepniak
Szymon Stepniak

Reputation: 42184

You can use String.startsWith(str) that returns true if env.GERRIT_PROJECT starts with platform/zap.

stage ('zap') {
    when {
        expression {
            env.GERRIT_PROJECT?.startsWith("platform/zap")
        }
    }
    steps {
        build job: 'Zap', parameters: [
            string(name: 'ZAP_PROJECT', value: env.GERRIT_PROJECT)
        ]
    }
}

To avoid NPE if env.GERRIT_PROJECT is null for some reason, you can use NPE-safe operator ?. to invoke startsWith method.

The alternative solution that uses Groovy's exact match operator with regex could look like this:

stage ('zap') {
    when {
        expression {
            env.GERRIT_PROJECT ==~ /^platform\/zap(.*)$/
        }
    }
    steps {
        build job: 'Zap', parameters: [
            string(name: 'ZAP_PROJECT', value: env.GERRIT_PROJECT)
        ]
    }
}

Upvotes: 6

Simon
Simon

Reputation: 667

https://jenkins.io/doc/book/pipeline/syntax/
Section environment:

environment
Execute the stage when the specified environment variable is set to the given value, for example: when { environment name: 'DEPLOY_TO', value: 'production' }

Maybe this can help?

Upvotes: 1

Related Questions